【问题标题】:How does one subtract hours from an NSDate?如何从 NSDate 中减去小时数?
【发布时间】:2010-11-12 18:09:51
【问题描述】:

我想从日期中减去 4 小时。我使用以下代码将日期字符串读入 NSDate 对象:

NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate * mydate = [dateFormatter dateFromString:[dict objectForKey:@"published"]];

接下来我该怎么做?

【问题讨论】:

  • (现在已经 6 年了,又过了 4 个 XCode 的主要版本……而且 NSDate 的功能仍然和 2009 年一样不直观!!)

标签: iphone objective-c nsdate


【解决方案1】:
NSDate *newDate = [theDate dateByAddingTimeInterval:-3600*4];

Link to documentation.


NSDate *newDate = [[[NSDate alloc] initWithTimeInterval:-3600*4
                                              sinceDate:theDate]] autorelease];

Link to documentation.

【讨论】:

    【解决方案2】:

    NSCalendar 是用于根据人类时间单位更改日期的通用 API。为此,您可以使用 NSCalendar 的 -dateByAddingComponents:toDate:options: 带负数的小时数。

    【讨论】:

    【解决方案3】:

    在 Swift 4 中:

    var baseDate = ... // something
    let dateMinus4Hours = Calendar.current.date(byAdding: .hour, value: -4, to: baseDate)
    

    不要使用24*3600 之类的东西,那是自找麻烦。

    【讨论】:

      【解决方案4】:

      iOS 8 以后有更方便的dateByAddingUnit

      Swift 2.x

      //subtract 3 hours
      let calendar = NSCalendar.autoupdatingCurrentCalendar()
      newDate = calendar.dateByAddingUnit(.Hour, value: -3, toDate: originalDate, options: [])
      

      【讨论】:

      • 评论说减去但是 3 被用作值,它应该是 -3
      【解决方案5】:
      //in Swift 3
      //subtract 3 hours
      let calendar = NSCalendar.autoupdatingCurrent
      newDate = calendar.date(byAdding:.hour, value: -3, to: originalDate)
      

      【讨论】:

        【解决方案6】:

        这里的函数可能很有用,因为它返回日期 -4 h,考虑到这也可能会更改日期和月份,最终会更改年份。 .searchBackward 选项是重要的部分:)

        public static func correctSecondComponent(date: Date, calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian))->Date {
        
            let hour = calendar.component(.hour, from: date)
        
            let e = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.hour, value: -4, to: date, options:.searchBackwards)!
        
            return e
        }
        

        【讨论】:

          【解决方案7】:

          dateFromString 函数返回 NSDate,而不是 NSString。 你应该改变,

          NSDate * theDate = [dateFormatter dateFromString:datetemp];

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-10-02
            • 2015-09-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-17
            • 2011-06-04
            相关资源
            最近更新 更多