Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT: How do I add hours to NSDate object

Tags:

ios

swift

nsdate

I generate a NSDate object from string.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let stringToDate = dateFormatter.dateFromString(dateFromService) // 2015-07-20 12:00:43 +0000

I get this string value from webserver. I need to modify for personal device timezone. Want to add hours this stringToDate object but not work

var addHours : Int = 2 // 2 hours will be added
var newDate = stringToDate.dateByAddingTimeInterval(addHours)
like image 589
Mehmet Avatar asked Jul 20 '15 12:07

Mehmet


1 Answers

Use NSCalendarComponents:

let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(
    .CalendarUnitHour, // adding hours
    value: 2, // adding two hours
    toDate: oldDate,
    options: .allZeros
)

Using NSCalendar will account for things like leap seconds, leap hours, etc.

But as Duncan C's answer points out, simply adding hours is definitely the wrong approach. Two time zones won't always be separated by the same amount of time. Again, this is something especially true when we take daylight savings into account. (For example, the United States doesn't start/end daylight savings on the same days as Europe, and Arizona doesn't even do daylight savings).

like image 67
nhgrif Avatar answered Oct 13 '22 19:10

nhgrif