4

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
A.Roe
  • 973
  • 3
  • 15
  • 34

1 Answers1

16

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.

Axel Guilmin
  • 11,454
  • 9
  • 54
  • 64
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 1
    Using `7 * 24 * 60 * 60` as the duration of a day is wrong. In regions with daylight summer time, a day may have 23 or 25 hours. The correct way is to use NSCalendar, see e.g. http://stackoverflow.com/a/27048988/1187415. – Martin R Jun 29 '16 at 04:29
  • @MartinR: Thank you. I updated my answer. – Luca Angeletti Jun 29 '16 at 08:40