【问题标题】:Is this the right way to add days to NSDate using NSDateComponents?这是使用 NSDateComponents 为 NSDate 添加天数的正确方法吗?
【发布时间】:2012-02-17 11:35:30
【问题描述】:

我正在使用以下方法从 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 天

案例 2:

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 小时。 这可能是什么问题? 有人遇到过这个问题吗?

【问题讨论】:

    标签: ios nsdate nsdatecomponents


    【解决方案1】:

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

    编辑:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2018-12-31
      相关资源
      最近更新 更多