我有一個類,它包含開始日期和結束日期,通常初始化爲本月的最後一秒。NSDate月加法和減法
以下功能才能正常工作從2010年11月向前進入十二月,然後再返回但是從十一月倒退結束了的startDate設爲
2010-09-30 23:00:00 GMT
即,一個月和一個小時前。
奇怪的結束日期仍然正確設置爲
2010-11-01 00:00:00 GMT
,還是今後每月從這個不正確的日期也導致在正確的時間和日期。
這是一個錯誤還是我正在做一些我不該做的事情?
-(void) moveMonth:(NSInteger)byAmount { // Positive or negative number of months NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease]; // Update the start date [components setMonth:byAmount]; NSDate *newStartDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0]; [self setStartDate:newStartDate]; // And the end date [components setMonth:1]; NSDate *newEndDate = [cal dateByAddingComponents:components toDate:[self startDate] options:0 ]; [self setEndDate:newEndDate]; }
SOLUTION:回答正確地指出,這是一個問題,DST
如果你要處理的絕對時間和日期,然後使用以下避免捲入任何DST。
NSCalendar *cal = [[NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"GMT"]; [cal setTimeZone:zone];
就是這樣,我很遺憾忘了。 – 2010-11-08 14:50:50