Home > Net >  Why is the time before 1892 printed incorrectly in Swift?
Why is the time before 1892 printed incorrectly in Swift?

Time:12-23

I came across a weird date behaviour in Swift.

If I try to print any date before 1891, the minutes and seconds will be printed incorrectly with offset by 2 minutes and 16 seconds like this:

Code Sample:

// incorrectly printed date
let year1981 = Calendar.current.date(from: .init(year: 1891, hour: 9))
print(year1981!) // will print 1891-01-01 08:02:16  0000

// correctly printed date
let year1982 = Calendar.current.date(from: .init(year: 1892, hour: 9))
print(year1982!) // will print 1892-01-01 08:00:00  0000

Is there any rational reason for this behaviour or it is a bug? Thanks for any reply!

Tested in Xcode Playground 14.1

CodePudding user response:

Based on the comments you are in the "Europe/Prague" timezone.

According to this website information:

When local standard time was about to reach
Thursday, October 1, 1891, 12:00:00 midnight clocks were turned forward 0:02:16 hours to
Thursday, October 1, 1891, 12:02:16 am local standard time instead.

This change would explain the results you are seeing when converting such a date.

So it is not a bug. It's just one of many examples of how complicated Date and Calendar code is due to all of the obscure details of time zones and day light saving time can be.

  • Related