Unexpected results when subtracting dates
Here is the code, for your viewing pleasure:
public static void main(String[] args) throws Exception {
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.form开发者_开发百科at(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?
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'.
http://en.wikipedia.org/wiki/ISO_8601#Times
精彩评论