Friday, June 11, 2010

Java Date Parsing down to the millisecond

Today I ran into a problem where a String needed to be converted into a java.util.Date. The String looked like this:


String date = "16MAR2010:09:08:27.126000";


So the code to parse the date was originally written like this:


String date = "16MAR2010:09:08:27.126000";

SimpleDateFormat format = new SimpleDateFormat("ddMMMyyyy:HH:mm:ss.SSSSSS");
Date value = format.parse(date);

System.out.println(value);



The problem was that the value printed out was several minutes ahead, 9:10 instead of 8:27. The problem turns out to be that the date parsing format does not allow more then 3 values of "S" in the milliseconds placeholder.

Solution
Strip off the last 3 zeros and change the parse pattern to


SimpleDateFormat format = new SimpleDateFormat("ddMMMyyyy:HH:mm:ss.SSS");

No comments: