Frank
Frank

Reputation: 4461

Java Calendar.getTimeInMillis

I'm trying to convert String timestamps of the form "201110250830" (yyyyMMddhhmm) to a number of milliseconds (a long). I'm using the following code:

Calendar t = Calendar.getInstance();
         t.set(Integer.parseInt(ts.substring(0,4)),
               Integer.parseInt(ts.substring(4,6)) - 1, // month is 0 based!
               Integer.parseInt(ts.substring(6,8)),
               Integer.parseInt(ts.substring(8,10)),
               Integer.parseInt(ts.substring(10,12)),
               0);
return t.getTimeInMillis();

However, I sometimes get an off by a few milliseconds discrepancy. For example:

long t1 = timestampToLong("201110250830");
long t2 = timestampToLong("201110250831");
assertEquals(60*1000, t2 - t1);

sometimes gives me:

Got exception: java.lang.AssertionError: expected:<60000> but was:<60001>

I checked the doc, but I couldn't find anything relevant. Any idea? (looks like a good day, I'm going to learn something here! :-)

Thanks!

Upvotes: 0

Views: 6070

Answers (2)

Dave Newton
Dave Newton

Reputation: 160191

Call t.clear() before calling set().

Welcome to the world of Java time/date handling.

Upvotes: 5

secmask
secmask

Reputation: 8107

you could using DateFormat like this.

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
Date ins = df.parse("201110250830");
long ts = ins.getTime();

Upvotes: 4

Related Questions