2010-12-01 81 views
5

我期待2010-10-11 00:00:00爲什麼NSCalendar的dateFromComponents返回錯誤的日期?

而是我收到2010-10-10 21:00:00 +0000

我知道,我可以添加了幾個小時,收到期望的日期,但我不明白爲什麼我前一天有21個小時...

請幫忙!

NSDateComponents *comps = [[NSDateComponents alloc] init]; 
[comps setYear:2010]; 
[comps setMonth:10]; 
[comps setDay:11]; 

[comps setHour:0]; 
[comps setMinute:0]; 
[comps setSecond:0]; 

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDate *retDate = [cal dateFromComponents:comps]; 

回答

15

我認爲你的問題可以通過設置NSTimeZone來解決。

+3

是的,你是對的! \t [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@「GMT」]];解決了這個問題 – 2010-12-01 09:16:10

0

如果您需要特定的時間格式,請使用該格式化程序,或者寫下此信息以獲取正確的時間。第一個選項...

let formatter = NSDateFormatter() 
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
    let localDate = formatter.dateFromString("1989-10-17T05:00:00.000-0000") 

,或者如果你的組件需要使用日期下面的代碼一樣......

let calendar = NSCalendar.currentCalendar() 
    calendar.timeZone = NSTimeZone(name: "GMT")! 
    let date = calendar.dateFromComponents(components) 

,或者您需要