0

我正在使用以下方法从 NSDate 中添加或减去天数。

当我记录这些值时,有时会得到意想不到的结果。

这是其中一种情况:

//This adds X days to the current Date and returns to the user
+(NSDate*)getRelativeDateInDays:(NSInteger)days forDate:(NSDate*)date{


    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *weekdayComponents = [[NSDateComponents alloc] init];
    [weekdayComponents setDay:days];
    NSDate *newDate = [gregorian dateByAddingComponents:weekdayComponents toDate:date options:0];
    [gregorian release];
    [weekdayComponents release];
    NSLog(@"start Date : %@ End Date %@",date,newDate);

返回新日期;}

情况1:

2012-02-17 06:28:14.474 申请[2906:707] 开始日期:2012-03-08 11:26:23 +0000 结束日期 2012-03-09 11:26:23 +0000 天数 1

案例二:

2012-02-17 06:29:00.631 申请[2906:707] 开始日期:2012-03-10 11:26:23 +0000 结束日期 2012-03-11 10:26:23 +0000 天数 1

在案例 1 中,当我将一天添加到 2012-03-08 11:26:23 +0000 时,我得到 2012-03-09 11:26:23 +0000。

但是,当我将一天添加到 2012-03-10 11:26:23 +0000 时,我得到 2012-03-11 10:26:23 +0000。

额外减少 1 小时。这里可能是什么问题?有人遇到过这个问题吗?

4

1 回答 1

2

这是因为夏令时 - 美国夏令时从 3 月 11 日开始。

编辑:

您可以通过将输入的日期转换为日期组件对象、更改日期组件(时间不受影响)然后转换回NSDate.

于 2012-02-17T11:42:59.773 回答