DateFormatter vs leap seconds

is this a bug that NSDateFormatter knows about leap days but not about leap seconds?

    let f = DateFormatter()
    f.timeZone = TimeZone(identifier: "UTC")
    f.dateFormat = "yyyy/MM/dd HH:mm:ss"
    // last leap year
    let t1 = f.date(from: "2020/02/29 00:00:00") // 2020-02-29 00:00:00 UTC
    // last leap second
    let t2 = f.date(from: "2016/12/31 23:59:60") // nil

Replies

Where did you get the notion of leap second ?

"2016/12/31 23:59:60" is an invalid date format, hence the nil result.

Similarly, not leap year in 2021, hence

let t1 = f.date(from: "2021/02/29 00:00:00")

gives nil

But consider the following:

let f = DateFormatter()
f.timeZone = TimeZone(identifier: "UTC")
f.dateFormat = "yyyy/MM/dd HH:mm:ss"
// last leap year
let t1 = f.date(from: "2020/02/29 00:00:00") // 2020-02-29 00:00:00 UTC
// last leap second
let t2 = f.date(from: "2016/12/31 23:59:59")! // not nil
let t3 = t2.addingTimeInterval(TimeInterval(1.0))
let t3Str = f.string(from: t3)
print("Leaped 1 second: ", t3Str)

You correctly get:

  • Leaped 1 second:  2017/01/01 00:00:00
  • "The next leap second will be added to the world’s clocks on December 31, 2016, at 23 hours, 59 minutes and 59 seconds Coordinated Universal Time (UTC). ... For anyone in the UTC±00:00 time zone, which includes London and the UK, the official clock will read 23.59.60 right before clicking over into 12.00.00 at midnight. (Normal clocks go from 23.59.59 to midnight.)"

    https://www.businessinsider.com/leap-second-added-december-31-2016-12

Add a Comment

Leap seconds are a long-running saga on macOS (and all Unix OSes).

If you periodically sync your time with a server, then things are generally fine.
But if you need to-the-second accuracy, while a leap-second is added, and you are performing date maths, then maybe not so good!

If you have developed a workaround, please share it here!