Search code examples
iosswifttimezonedateformatter

iOS 10 timezone format trouble with dates created as timeIntervalSince1970


Before I file a radar I would like to doublecheck if I am not missing something (and learn from this). Here is my test code from a Swift 3 playground (code behaves the same in my app). I am currently working in the timezone "Europe/Lisbon" which in February is the same as GMT.

import UIKit

let date =  Date(timeIntervalSince1970: 0)
var formatter = DateFormatter()
formatter.dateFormat = "HH:mm"

print(TimeZone.current.abbreviation()!) // GMT

formatter.timeZone = TimeZone.current
print(formatter.string(from: date)) // 01:00

formatter.timeZone = TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())
print(formatter.string(from: date)) // 00:00

formatter.timeZone = TimeZone(identifier: "Europe/London")
print(formatter.string(from: date)) // 01:00

formatter.timeZone = TimeZone(identifier: "America/Los_Angeles")
print(formatter.string(from: date)) // 16:00

Somehow the formatted time is one hour off except when I set the Timezone as

TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())

Is this expected behavior? Thanks!


Solution

  • The results are in fact correct, because in the year 1970 the "Europe/Lisbon" timezone was "UTC+1":

    let tz = TimeZone(identifier: "Europe/Lisbon")!
    
    print(tz.secondsFromGMT())
    // Output: 0
    
    print(tz.secondsFromGMT(for: Date(timeIntervalSince1970: 0)))
    // Output: 3600
    

    so that midnight on "Jan 1, 1970 GMT" was one o'clock in the morning in Lisbon.

    You can lookup the timezones and daylight saving time periods for past and future years at https://www.timeanddate.com/time/zone/portugal/lisbon.