Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days/hours to NSDate with Swift [duplicate]

Tags:

swift

nsdate

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.

like image 558
A.Roe Avatar asked Dec 05 '22 17:12

A.Roe


1 Answers

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.

like image 60
Luca Angeletti Avatar answered Jan 07 '23 00:01

Luca Angeletti