Matt Ball Matt Ball - 3 months ago 13
Java Question

Inconsistent date parsing using SimpleDateFormat

I'm really scratching my head on this one. I've been using

SimpleDateFormat
s with no troubles for a while, but now, using a SimpleDateFormat to parse dates is (only sometimes) just plain wrong.

Specifically:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());


prints the string
Wed Aug 19 00:00:00 EDT 2009
. What the heck? - it doesn't even parse into the wrong date all the time!




Update: That fixed it beautifully. Wouldn't you know it, that was misused in a few other places as well. Gotta love debugging other people's code :)

Answer

I think you want to use the HH format, rather than 'hh' so that you are using hours between 00-23. 'hh' takes the format in 12 hour increments, and so it assumes it is in the AM.

So this

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());

Should print out

Wed Aug 19 12:00:00 EDT 2009