我有一个类,它包含开始日期和结束日期,通常初始化为本月的最后一秒。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