【问题标题】:Adding 30 seconds to NSDate [duplicate]向 NSDate 添加 30 秒 [重复]
【发布时间】:2015-12-28 00:47:43
【问题描述】:

如何将NSDate 转换为秒?我需要它在几秒钟内,以便我可以将日期添加 30 秒,然后转换回 NSDate 以安排本地通知。也欢迎任何更好的方法。

【问题讨论】:

    标签: ios cocoa-touch nsdate uilocalnotification date-arithmetic


    【解决方案1】:

    Date and Time Programming Guide 声明应使用NSDateComponents 执行日期计算。

    引用同一文档:

    您应该使用提供的方法来处理日历计算,因为它们考虑到了极端情况,例如夏令时开始或结束以及闰年。

    所以要给日期增加 30 秒,你应该这样做:

    NSDate * date = [NSDate date];
    NSCalendar * currentCalendar = [NSCalendar currentCalendar];
    NSDateComponents * dateComponents = [NSDateComponents new];
    
    [dateComponents setSecond:30];
    
    NSDate * newDate = [currentCalendar dateByAddingComponents:dateComponents toDate:date options:0];
    
    NSLog(@"%@", newDate);
    

    【讨论】:

      【解决方案2】:

      您可以使用 dateByAddingTimeInterval 并将值作为 30 传递。这将返回一个 NSDate,它将提前 30 秒。

      NSDate *newDate = [previousDate dateByAddingTimeInterval:30];
      

      【讨论】:

        猜你喜欢
        • 2016-10-31
        • 1970-01-01
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多