A.Roe A.Roe - 1 year ago 105
Swift Question

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

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

Answer Source

You can use dateByAddingTimeInterval do build a new instance of NSDate adding the delta seconds.

let now = NSDate()
let sevenDaysAgo = now.dateByAddingTimeInterval(-7 * 24 * 60 * 60)
let sevenDaysAnd1HourAgo = sevenDaysAgo.dateByAddingTimeInterval(-1 * 60 * 60)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download