2015-06-17 24 views
0

有兩種結局天像beloew解析日期和1獲得了一天假,NSDate的

A = 2029-12-31T00:00:00+00:00 
B = 2029-12-31T12:00:00+00:00 

我按照

NSDateFormatter *endDateFormatter = [[NSDateFormatter alloc] init]; 
[endDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; 
NSDate *endDate = [endDateFormatter dateFromString:self[@"license"][@"endDate"]]; 
NSDateComponents *endDatecomponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:endDate]; 

讓月,日和年這是我得到對於A

Printing description of endDate: 
2029-12-31 00:00:00 +0000 
Printing description of endDatecomponents: 
<NSDateComponents: 0x79e069e0> 
    Calendar Year: 2029 
    Month: 12 
    Leap month: no 
    Day: 30 

對於B,我越來越

2029-12-31 12:00:00 +0000 
Printing description of endDatecomponents: 
<NSDateComponents: 0x7be8eb60> 
    Calendar Year: 2029 
    Month: 12 
    Leap month: no 
    Day: 31 

我很困惑爲什麼2029-12-31T00:00:00+00:00只給我一天休息1天。 對此有何想法?

回答

2

這是由於您的時區和UTC之間的差異。值爲2029-12-31T00:00:00+00:00的時區爲UTC時區的12月31日。但是當你設置日期組件時,你會在當地時間12月30日的時區獲取日期。

+0

我試圖阻止UTC轉換爲本地時區,但它確實有所幫助。任何想法從UTC恢復12月31日。 ? – tonytran

+0

我找到了解決問題的方法。事實證明,我必須使用'NSCalendar * utcCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [utcCalendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@「UTC」]];' – tonytran