Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date difference in Java 23 hours day

Tags:

java

date

I have to calculate the difference between to dates, I have found a way but I have this strange result, Am I missing something?

public static void main(String[] args) throws ParseException {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    long result = format.parse("2012-03-25 24:00").getTime() - format.parse("2012-03-25 00:00").getTime();
    System.out.println("Difference in hours: " + result/(1000*60*60));
    result = format.parse("2012-03-26 24:00").getTime() - format.parse("2012-03-26 00:00").getTime();
    System.out.println("Difference in hours: " + result/(1000*60*60));
}

This is the result: Difference in hours: 23 Difference in hours: 24

Thanks for the advices, now I'm using the Joda libray, I have this question, when I calculate the difference in this way:

DateTime  begin = new DateTime("2012-03-25T00:00+01:00");
DateTime  end = new DateTime("2012-03-26T00:00+01:00");
Hours m = Hours.hoursBetween(begin, end);

If I use this way to calculate the hours I get 24 hours (because the DST is not considered I assume)

What class/calculus should I use in order to get as result the 23 hours considering the DST (I have already tried different ways but I don't get it) the Period class?

Thanks for all the help...

like image 821
user1847243 Avatar asked Nov 23 '12 10:11

user1847243


1 Answers

Chances are you happen to have picked a date where daylight saving time changed in that time zone, so the day could really have been only 23 hours long. (March 25th 2012 certainly was the DST change date for Europe, e.g. Europe/London. We don't know what your default time zone is though.)

If you set your date format to use UTC, you shouldn't see this effect. (It's somewhat odd to use 24:00 in a string representation, mind you.) It's not clear what your data is meant to represent though, or what you're trying to measure. You should work out what time zone your data is really meant to be in, if you want to work out how much time actually elapsed between those local times.

(As noted in another answer, Joda Time is a much better API in general - but you still need to know how to use it properly, and when trying to work out the actual elapsed time, you'd still have seen the same results here.)

like image 122
Jon Skeet Avatar answered Nov 20 '22 20:11

Jon Skeet