Search code examples
javadatetimeclojurejodatimeclj-time

Time difference respecting day light savings


I have two longs representing time since the epoch. They both have the same timezone. I want to find the difference in seconds between these two times, respecting day light savings.

(def a (java.util.Date. 1259568796000))  ;; Before Day Light Savings

(def b (java.util.Date. 1255147200000))  ;; After Day Light Savings

Where 'a' is 2009-11-30T08:13:16.000-00:00

and

Where 'b' is 2009-10-10T04:00:00.000-00:00

Using JodaTime, I can make an Interval out of these two times, turn them into a Duration, and get the StandardSeconds.

(.getStandardSeconds (.toDuration (Interval. a b)))

This doesn't work though, because the docs for Period indicate that Duration will mess up Day Light Savings:

When this time period is added to an instant, the effect is of adding each field in turn. As a result, this takes into account daylight savings time. Adding a time period of 1 day to the day before daylight savings starts will only add 23 hours rather than 24 to ensure that the time remains the same. If this is not the behaviour you want, then see Duration.

How can I accomplish this task?


Solution

  • The long in Java represents a certain point in time (milliseconds since midnight on 1.1.1970, ignoring leap seconds). They don't carry a time zone and do not switch with daylight savings time, it is always expressed in UTC. To find the difference in seconds between two such timepoints you can use

    (secondTime - firstTime) / 1000
    

    The two times you have given are expressed in GMT, i.e.

    1259568796000 = 2009-11-30T08:13:16.000-00:00 GMT
    1255147200000 = 2009-10-10T04:00:00.000-00:00 GMT
    

    And GMT does not switch to daylight savings time either. Maybe you were confused by that.