How To Use TimeZone Correctly

- 1 answer

I have following code in Swift 4 for iOS

    var dateComponents = DateComponents()
    var datetime = Date()
    dateComponents.timeZone = Calendar.current.timeZone = Calendar.current.component(.day, from: datetime)
    dateComponents.month = Calendar.current.component(.month, from: datetime)
    dateComponents.year = Calendar.current.component(.year, from: datetime)
    dateComponents.hour = 12
    dateComponents.minute = 45 
    datetime = dateComponents)!

and it produces this output:

Europe/Prague (current)

2017-12-26 11:45:00 +0000

whilst I expect

2017-12-26 12:45:00 +0000

due to timezone specified. What I have to do differently? Thanks.



The 2017-12-26 11:45:00 +0000 is showing you the date in GMT/UTC/Zulu (that's what the +0000 means). Bottom line, 12:45pm on 26 Dec 2017 in Prague is 11:45 GMT.

The description property of a Date (which is what is used if you just print a Date) always returns a string shown in GMT. If you want to see it in your local timezone, you'd use a date formatter to convert a date to a string, e.g.

let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .medium
print(formatter.string(from: datetime))

Bottom line, if you want to display the date in the user interface of your app (where you want to show it in their local time zone), always use a date formatter. Like DateComponents, the time zone of DateFormatter defaults to the current time zone.

Note, I avoided using dateFormat property of the DateFormatter because whenever showing a date string in an app UI, you want to use a localized string (the date shown in a format preferred by the end user, as specified in the Settings app). The easiest way to achieve this is use dateStyle and timeStyle as shown above.