Converting string to milliseconds

user2177467 picture user2177467 · Mar 16, 2013 · Viewed 13.8k times · Source

I want to calculate the time difference between two dates (in the format "yyyyMMddHHmmss"). The basic idea is to first convert the string date into milliseconds and then get the time difference.

Calendar c1 = Calendar.getInstance();
c1.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse("20110327032913"));
System.out.println(c1.getTimeInMillis());
Calendar c2 = Calendar.getInstance();
c2.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse("20110327025913"));     
System.out.println(c2.getTimeInMillis());

Result:

1301189353000

1301191153000

Obviously, the first date is later than the second one, but its converted millisecond is smaller. Did I make any error on format?

Answer

harpun picture harpun · Mar 16, 2013

The time difference between the two timestamps in ms is 30 minutes:

1301191153000 - 1301189353000 = 1800000ms = 30 min

Because of the DST changes on 27 march, the clock is being set forward at 2 AM from 2 AM to 3 AM, hence the timestamps:

20110327032913 => 2011-03-27 03:29:13

20110327025913 => 2011-03-27 02:59:13

are in fact interpreted as:

2011-03-27 03:29:13

2011-03-27 03:59:13 (+1 hour from original time)

Thus, the second timestamp comes later and when converted to ms it is bigger than the first one.