2016-02-26 113 views
0

我目前在時區UTC-05:00。當我調用該函數NSDate(timeIntervalSince1970:0),它返回「1969年12月31日,下午7:00」如何從NSDate獲得當前時區的年月日

let date = NSDate.init(timeIntervalSince1970: 0) // "Dec 31, 1969, 7:00 PM" 
print(date) // "1970-01-01 00:00:00 +0000\n" 

我讀到這個How to get NSDate day, month and year in integer format?但問題是,隨着下面,我總是1969-12-31由於5小時的時差。

let calendar = NSCalendar.currentCalendar() 
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date) 
year // 1969 
month // 12 
day // 31 

var hour = 0, minute = 0, second = 0 
calendar.getHour(&hour, minute: &minute, second: &second, nanosecond: nil, fromDate: date) 
hour  // 19 
minute  // 0 
second  // 0 

有沒有辦法在當前時區獲取當前的年,月,日值等。我所尋找的是在這裏:

year // 1970 
month // 01 
day // 01 
+0

'NSTimeZone systemTimeZone' – zcui93

+1

隨着'0 timeIntervalSince1970',那是你本地的正確信息時區。 –

+1

這裏的問題是您要求的日期已被固定爲UTC 0。除非將此日曆的時區更改爲UTC 0,否則您將始終得到該結果。 –

回答

2

timeIntervalSince1970初始化給你(如記錄)的NSDate這是自1970年1月1日秒一定數量00:00:00 在UTC,而不是在你的當地時區。你得到的結果是正確的,因爲它們顯示的是當地時區與當時的偏移量。你傳遞0,所以你得到1970年1月1日00:00:00 UTC,然後NSCalendar給你在當地時區的等效日期和時間。

如果你想在你的本地時區獲得1970年1月1日00:00:00,則需要從NSCalendar明確要求日期:

let calendar = NSCalendar.currentCalendar() 
calendar.timeZone = NSTimeZone.localTimeZone() 

let date = calendar.dateWithEra(1, year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0) 
calendar.getEra(&era, year:&year, month:&month, day:&day, fromDate: date!) 
year // 1970 
month // 1 
day // 1 

這不是一個0 timeIntervalSince1970偏移。如果你檢查,你會發現結果與你的時區與UTC的偏移:

date?.timeIntervalSince1970 // 25200, for me 
1

這將返回當前日期前。 02/26/2016

// Format date so we may read it normally 
let dateFormatter = NSDateFormatter() 
dateFormatter.dateFormat = "dd/M/yyyy" 
let currentDate = String(dateFormatter.stringFromDate(NSDate())) 

雨燕3.0

NSDateFormatter>DateFormatter & & NSDate>Date

let df = DateFormatter() 

df.timeZone = .current 
df.dateStyle = .medium 
df.timeStyle = .short 
df.dateFormat = "dd/M/yyyy" 

let currentDate = df.string(from: Date()) 
相關問題