Take the 2-minute tour ×

Here is the code, for your viewing pleasure:

    Calendar cal = Calendar.getInstance();
    cal.set(2010, Calendar.JULY, 10, 1, 0, 20);
    Date d1 = cal.getTime();
    Date d2 = new Date();
    int seconds = 22;
    d2.setTime(d1.getTime() - seconds*1000);
    SimpleDateFormat iso_format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
    System.out.println(iso_format.format(d1) + " - " + seconds + "s = " + iso_format.format(d2));

Output: 2010-07-10 01:00:20 - 22s = 2010-07-10 24:59:58

Shouldn't the answer be 2010-07-09 24:59:58? Why does it loop back to the same day? Is there a way to fix it?

share|improve this question
better question: why it is not 2010-07-10 00:59:58 (22 seconds before 1:00:20) –  DennyRolling Nov 8 '10 at 2:12
even worse: times such as 24:59:58 don't happen, the clock goes from 23:59:59 to 00:00:00 (leap seconds aside). –  High Performance Mark Nov 8 '10 at 2:12
@High: when using the k format specifier, the hour field ∈ [1,24] not [0, 23]. –  Matt Ball Nov 8 '10 at 2:22
Why in the world would anyone want an hour format specifier that's ∈ [1,24]? –  Michael Kopinsky Nov 8 '10 at 2:30
add comment

1 Answer

up vote 3 down vote accepted

the hour 24 (since you used 'kk' to format) is considered the next day, ie the 10th. it is equivalent to midnight. I use 'HH' to format hours, which would display the 24th hour as '00'. this makes more sense to me and i believe is more standards compliant.

the date changes over at the 00/24th hour. if you were to subtract another hour from the resulting date, the date would become the 9th as expected.

also, if you want true ISO time format 'HH' is better than 'kk'.


share|improve this answer
add comment

Your Answer


