【问题标题】:NSDate and the next dayNSDate 和第二天
【发布时间】:2011-07-31 00:21:14
【问题描述】:

我以前做的是使用时间戳,然后添加 86400 秒( 24 * 60 * 60 )。当我阅读最近关于 stackoverflow 的一个问题时,指出这并不是每天都正确的,我想改变它。

所以我想出的下一件事是使用 NSDateComponents。我只是得到当天并加 1。现在我想知道这有多“聪明”。就像如果天等于 31,它是否将天设置为 1,将月份设置为 +1(或者再次设置为 12 到 1)?我可以手动执行此操作,但这仅适用于公历,所以我也不知道这是否是一个好的解决方案..

【问题讨论】:

    标签: objective-c cocoa macos nsdate


    【解决方案1】:

    它很聪明,除非你想让它变笨。

    来自the documentation for -[NSCalendar dateByAddingComponents:toDate:options]

    如果您未指定任何选项(您传递 0),则单元中的溢出会进入更高的单元(如典型的加法)。

    如果您确实希望单位溢出到更高的单位,那么您将传递“NSWrapCalendarComponents”作为options: 参数的值。

    【讨论】:

    • 酷,谢谢——是你的推文通知了我代码中的这个错误顺便说一句:P
    【解决方案2】:

    要非常小心 DST。不同时区的情况不同。 而且它发生在午夜 我相信,如果您通过添加组件调用 [NSCalendar 日期:toDate:options] 并且您的日期在晚上 11 点到 12 点之间,那么您可能会因为 DST 而错过或重新运行一天。 要解决此问题,建议将日期更改为当天中午,然后添加日期。

    // increment by 1 calendar day
    // and convert back to NSDate objects
    NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
    [comps setDay:1];
    
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    [gregorian setTimeZone:self.myTimeZone]; // time zone of location;  
    
    // Use local noontime for the date to avoid problems around
    // midnight, particularly near daylightsavings time discontinuities. 
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents* dateComponents = [gregorian components:unitFlags fromDate:date];
    
    dateComponents.hour = 12;
    NSDate* noonDate = [gregorian dateFromComponents:dateComponents];
    
    NSDate *newDate = [gregorian dateByAddingComponents:comps toDate:noonDate options:0];
    

    我不确定 options:0 设置,但我确实对此进行了彻底的测试。我用它来获取一个包含 10 天日期的数组。它可以正确地环绕各种日/月/年的不连续性。如果您想对其进行测试,请查看应用商店中的 SunPose Rise Set。 (是的,它是免费的)

    【讨论】:

      猜你喜欢
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2019-01-19
      相关资源
      最近更新 更多