1

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?

Mike
  • 19,267
  • 11
  • 56
  • 72

2 Answers2

3

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.

Henry
  • 42,982
  • 7
  • 68
  • 84
  • Subtraction yields 4421596 seconds, which is incorrect. It is one hour off. – Mike Dec 12 '13 at 21:15
  • 1
    @Mike it yields the seconds elapsed between the two points in time. Note that this is not the same as the difference between the two wall clock readings at these times. There is a difference of one hour. I thought this is exactly what you were asking for. – Henry Dec 12 '13 at 21:21
  • Hm, I think I just poorly explained it. Sorry @Henry. – Mike Dec 13 '13 at 14:25
0

The java.util.Calendar class has support for daylight savings. Perhaps run your dates through that first? It should do the normalization for you. Check out this other post.

Community
  • 1
  • 1
samsquanch
  • 521
  • 3
  • 12