I must use a SimpleDateFormat
to parse a date in Java. I'm using an existing library that takes a date as String
and a SimpleDateFormat
instance to parse it.
Everything is fine, but I'm having trouble if the date format consists in only milliseconds since epoch time (1/1/1970), i.e. UNIX time in milliseconds. Using new SimpleDateFormat("SS")
or new SimpleDateFormat("SSS")
didn't work:
Code to reproduce the strange SimpleDateFormat
behavior:
TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // just for the test
long currTimeInMilli = System.currentTimeMillis();
SimpleDateFormat msSDF = new SimpleDateFormat("SS"); // same result with SimpleDateFormat("SSS")
SimpleDateFormat secSDF = new SimpleDateFormat("ss");
System.out.println(msSDF.parse("" + currTimeInMilli));
System.out.println(secSDF.parse("" + (currTimeInMilli / 1000)));
System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy").format(currTimeInMilli));
Produced output:
Mon Dec 15 07:46:20 GMT 1969 <-- should be like two other lines (?)!
Mon Apr 28 20:55:19 GMT 2014 <-- OK
Mon Apr 28 20:55:19 GMT 2014 <-- OK
Is it normal? How can I set up a SimpleDateFormat
able to parse milliseconds elapsed since the epoch?
Notes:
new Date(long pNbMilli)
to construct the date (legacy library is taking a SimpleDateFormat
instance as input)The S
pattern won't properly handle a number of milliseconds greater than Integer.MAX_VALUE
, as bizarre as that may seem for a quantity normally expressed as a long.
If you really must use an existing API that demands a DateFormat you can always hack it in:
SimpleDateFormat msSDF = new SimpleDateFormat("SSS") {
@Override
public Date parse(String source) throws ParseException {
return new Date(Long.parseLong(source));
}
};
(May need to also provide a hacked implementation of format(string)
too depending on what your legacy API actually does of course.)