Matt Ball Matt Ball - 1 year ago 69
Java Question

Inconsistent date parsing using SimpleDateFormat

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

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


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

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 Source

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");

Should print out

Wed Aug 19 12:00:00 EDT 2009

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download