2010-11-08 58 views
2

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

回答

5

这可能不是一个错误,而是与10月到11月期间DST变化相关的问题。

+0

就是这样,我很遗憾忘了。 – 2010-11-08 14:50:50

1

仅抓取当前日期的月份和年份,添加/减去月份数差异,然后从这些新值中生成日期会更容易。没有必要担心夏令时,闰年,等等。像这样的事情应该工作:

-(void) moveMonth:(NSInteger)byAmount { 
    NSDate *now = [NSDate date]; 
    NSCalendar *cal = [NSCalendar currentCalendar]; 

    // we're just interested in the month and year components 
    NSDateComponents *nowComps = [cal components:(NSYearCalendarUnit|NSMonthCalendarUnit) 
             fromDate:now]; 
    NSInteger month = [nowComps month]; 
    NSInteger year = [nowComps year]; 

    // now calculate the new month and year values 
    NSInteger newMonth = month + byAmount; 

    // deal with overflow/underflow 
    NSInteger newYear = year + newMonth/12; 
    newMonth = newMonth % 12; 

    // month is 1-based, so if we've ended up with the 0th month, 
    // make it the 12th month of the previous year 
    if (newMonth == 0) { 
     newMonth = 12; 
     newYear = newYear - 1; 
    } 

    NSDateComponents *newStartDateComps = [[NSDateComponents alloc] init]; 
    [newStartDateComps setYear: year]; 
    [newStartDateComps setMonth: month]; 
    [self setStartDate:[cal dateFromComponents:newDateComps]]; 
    [newDateComps release]; 

    // Calculate newEndDate in a similar fashion, calling setMinutes:59, 
    // setHour:23, setSeconds:59 on the NSDateComponents object if you 
    // want the last second of the day 
} 
0

这里是一个方式做正确。此方法在添加/减去月份“byAmount”后返回新的NSDate。

-(NSDate*) moveMonth:(NSInteger)byAmount { 

    NSDate *now = [NSDate date]; 

    NSDateComponents *components = [[NSDateComponents alloc] init]; 
    [components setMonth:byAmount]; 

    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:now options:0]; 

    return newDate; 
}