Does your language handle leap second?

by Paweł Świątkowski
29 Jun 2015

Every once in a while (some people approximate it with ‘about two years’) an extra second is added to calendar to make our atomic time more aligned with solar time. The reason for that are irregularities in how the earth spins around. The need to adjust an extra second is issued by International Earth Rotation and Reference Systems Service (which is, by the way, a cool name to have in your CV, if you have a chance). It happend in 2012, causing quite a mess, and it will happen soon. More precisely, tomorrow (30.06.2015).

How does it look in practice? An extra second is added at the end of the day in UTC, so the time goes as follows:

23:59:58
23:59:59
23:59:60 <- leap second
00:00:00
00:00:01

Does your language reflect it? Sadly, the answer is most probably: no. You won’t have any luck in JavaScript:

> d1 = new Date(Date.UTC(2015, 6, 1, 0, 0, 0))
Wed Jul 01 2015 02:00:00 GMT+0200 (CEST)
> d2 = new Date(Date.UTC(2015, 5, 30, 23, 59, 59))
Wed Jul 01 2015 01:59:59 GMT+0200 (CEST)
> d1 - d2
1000

… or Ruby …

[10] pry(main)> t1 = Time.new(2015, 7, 1, 2, 0, 0).utc
=> 2015-07-01 00:00:00 UTC
[11] pry(main)> t2 = Time.new(2015, 7, 1, 1, 59, 59).utc
=> 2015-06-30 23:59:59 UTC
[12] pry(main)> t1 - t2
=> 1.0

… or Erlang …

1> Date1 = {{2015,7,1}, {0,0,0}}.
{{2015,7,1},{0,0,0}}
2> Date2 = {{2015,6,30},{23,59,59}}.    
{{2015,6,30},{23,59,59}}
3> calendar:time_difference(Date2,Date1).
{0,{0,0,1}}
4> Date3 = {{2015,6,30},{23,59,60}}.     
{{2015,6,30},{23,59,60}}
5> calendar:time_difference(Date1,Date3).
{0,{0,0,0}}

The reason for that seems to be explained in DataStax’s article

From the Linux time system’s point of view, the last second of June 30th will repeat itself as another second with the same timestamp as the one previous is inserted at the end of the day.

So, basically, the system will have 23:59:59 twice and we cannot really know what second this is really about. If you have some code relying on time differences, you are probably on your own with taking care of that condition. Other strategy was chosen by Amazon in AWS - they decided to add a fractions of second during few hours surrounding the leap second moment, thus minimizing impact of a “misplaced” second itself. As it seems for Windows, they ignore leap second totally and time gets synchronized on next request.

end of the article

Tags: ruby javascript erlang linux

This article was written by me – Paweł Świątkowski – on 29 Jun 2015. I'm on Fediverse (Ruby-flavoured account, Elixir-flavoured account). Let's talk.