【问题标题】:Objective C - get the following day from today (tomorrow)目标C - 从今天(明天)开始的第二天
【发布时间】:2012-09-22 19:35:52
【问题描述】:

如何检查某个日期是否天生就是 TOMORROW?

我不想为今天这样的日期添加小时或任何内容,因为如果今天已经是 22:59,添加太多会转到后天,如果时间是 12:00,添加太少明天会错过。

我如何检查两个NSDates 并确保其中一个相当于明天的另一个?

【问题讨论】:

标签: iphone objective-c ios cocos2d-iphone


【解决方案1】:

您或许可以利用NSCalendar/Calendar 创造明天:

extension Calendar {
    var tomorrow: Date? {
        return date(byAdding: .day, value: 1, to: startOfDay(for: Date()))
    }
}

【讨论】:

    【解决方案2】:

    在 iOS 8 中,NSCalendar 上有一个方便的方法,称为 isDateInTomorrow

    目标-C

    NSDate *date;
    BOOL isTomorrow = [[NSCalendar currentCalendar] isDateInTomorrow:date];
    

    斯威夫特 3

    let date: Date
    let isTomorrow = Calendar.current.isDateInTomorrow(date)
    

    斯威夫特 2

    let date: NSDate
    let isTomorrow = NSCalendar.currentCalendar().isDateInTomorrow(date)
    

    【讨论】:

      【解决方案3】:

      使用NSDateComponents,您可以从代表今天的日期中提取日/月/年分量,忽略小时/分钟/秒分量,添加一天,并重建对应于明天的日期。

      假设您想在当前日期中添加一天(包括保持小时/分钟/秒信息与“现在”日期相同),您可以在“现在”中添加 24*60*60 秒的 timeInterval " 使用dateWithTimeIntervalSinceNow,但最好使用NSDateComponents 这样做(以及防夏令时等):

      NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
      [deltaComps setDay:1];
      NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];
      

      但是如果您想生成对应于明天午夜的日期,您可以改为只检索代表现在的日期的月/日/年组件,没有小时/分钟/ secs 部分,并添加 1 天,然后重建一个日期:

      // Decompose the date corresponding to "now" into Year+Month+Day components
      NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
      NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
      // Add one day
      comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
      // Recompose a new date, without any time information (so this will be at midnight)
      NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
      

      P.S.:您可以在 Date and Time Programming Guide,尤其是 here about date components 中阅读有关日期概念的非常有用的建议和资料。

      【讨论】:

      • 您如何解决NSCalendardateFromComponents 返回nullable 结果这一事实?我知道明天总是存在的,并且想在编码时使用这个事实。但是,当我在 Swift 中使用这种方法时tomorrowMidnight可能nil,至少编译器是这样认为的。
      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多