【问题标题】:Subtract minutes from NSDate从 NSDate 中减去分钟
【发布时间】:2011-02-14 04:32:49
【问题描述】:

我想减去一些分钟 15 分钟 10 分钟等,我现在有带时间的日期对象,现在我想减去分钟。

【问题讨论】:

    标签: ios nsdate nstimeinterval


    【解决方案1】:

    使用以下:

    // gives new date object with time 15 minutes earlier
    NSDate *newDate = [oldDate dateByAddingTimeInterval:-60*15]; 
    

    【讨论】:

    • @Ishu 确保您没有传递无符号整数。我犯了那个错误。
    • 这更简单,但它会遗漏一些边缘情况(例如闰秒)。假设一分钟有 60 秒、一小时有 60 分钟或任何其他快捷方式,这适用于任何时候看到的东西。使用此问题的其他 NSCalendar 答案会利用已经为您处理所有边缘情况的现有功能集。
    【解决方案2】:

    查看我对这个问题的回答:NSDate substract one month

    这是一个示例,已针对您的问题进行了修改:

    NSDate *today = [[NSDate alloc] init];
    NSLog(@"%@", today);
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setMinute:-10]; // note that I'm setting it to -1
    NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
    NSLog(@"%@", endOfWorldWar3);
    

    希望这会有所帮助!

    【讨论】:

    • NSGregorianCalendar 从 iOS 8 开始被弃用。也许我们可以更新这个答案。
    【解决方案3】:

    iOS 8 以后有更方便的dateByAddingUnit

    //subtract 15 minutes
    let calendar = NSCalendar.autoupdatingCurrentCalendar()
    newDate = calendar.dateByAddingUnit(.CalendarUnitMinute, value: -15, toDate: originalDate, options: nil)
    

    【讨论】:

      【解决方案4】:

      从 Swift 2.x 开始,当前的 Swift 答案已经过时。这是一个更新的版本:

      let originalDate = NSDate() // "Jun 8, 2016, 12:05 AM"
      let calendar = NSCalendar.currentCalendar()
      let newDate = calendar.dateByAddingUnit(.Minute, value: -15, toDate: originalDate, options: []) // "Jun 7, 2016, 11:50 PM"
      

      NSCalendarUnitOptionSetType 的值已更改为 .Minute,您不能再将 nil 传递给 options。而是使用一个空数组。

      使用新的 DateCalendar 类更新 Swift 3:

      let originalDate = Date() // "Jun 13, 2016, 1:23 PM"
      let calendar = Calendar.current
      let newDate = calendar.date(byAdding: .minute, value: -5, to: originalDate, options: []) // "Jun 13, 2016, 1:18 PM"
      

      为 Swift 4 更新上面的代码:

      let newDate = calendar.date(byAdding: .minute, value: -5, to: originalDate) // "Jun 13, 2016, 1:18 PM"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2011-01-19
        相关资源
        最近更新 更多