SWIFT: How do I add hours to NSDate object

后端 未结 4 1728
逝去的感伤
逝去的感伤 2021-01-02 18:18

I generate a NSDate object from string.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = \"yyyy-MM-dd HH:mm:ss\"
dateFormatter.timeZone = NS         


        
4条回答
  •  醉梦人生
    2021-01-02 19:00

    If you are doing it more often, check out library called SwiftMoment (inspired by the same .js library), which allows you to do following (and much more!):

    // Create date using moment library
    let myDate = moment(myString)
    
    // Add one hour
    let dateWithAddedHour = myDate + 1.hours
    

    Moment is a wrapper around NSDate instance, while Duration (which is what you get from Int.hours, Int.minutes etc.) wraps an NSTimeInterval value.

    Implementing this should take you just a moment! (Pun intended).

提交回复
热议问题