Mehmet Mehmet - 1 month ago 16
Swift Question

SWIFT: How do I add hours to NSDate object

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)

Answer

You're asking the wrong question. This is what's known as an "XY Problem". You should be asking "How do I display a date string I get from a web server in the user's local time zone."

NSDate represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.

The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let date = dateFormatter.dateFromString(dateFromService) 

let outputDatedateFormatter = NSDateFormatter()
outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//leave the time zone at the default (user's time zone)
let displayString = outputDateFormatter.stringFromDate(date)
println("Date in local time zone = \(displayString)")