Search code examples
swiftnsdate

Adding days/hours to NSDate with Swift


I know it is a really basic question, and I am aware I might not be finding the answer because I am not asking the right question however how can I change the NSDate value ?

For Example I have a date property which is set to the date of a datePicker and I want to create a new property which is the day before the date property and another which is an hour before.


Solution

  • Adding and removing days

    In order to avoid problems with daylight summer time, when you are adding days you should use NSCalendar

    Swift 3 :

    let tomorrow = Calendar.current.date(byAdding:
        .day, // updated this params to add hours
        value: 1,
        to: now)
    

    Swift 2 :

    let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day, // updated this params to add hours
        value: 1,
        toDate: now,
        options: .MatchFirst)
    

    Please note that you are NOT mutating the original instance (now), you are simply building a new one. Infact the NSDate class is immutable.