views:

860

answers:

3

I'm really scratching my head on this one. I've been using SimpleDateFormats 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 :)

+2  A: 

You're printing out the toString() representation of the date, rather than the format's representation. You may also want to check the hour representation. H and h mean something different. H is for the 24 hour clock (0-23), h is for the 12 hour clock (1-12), (there is also k and K for 1-24 and 0-11 based times respectively)

You need to do something like:

//in reality obtain the date from elsewhere, e.g. new Date()
Date date = sdf.parse("2009-08-19 12:00:00"); 

//this format uses 12 hours for time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//this format uses 24 hours for time
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.print(sdf.format(date));
System.out.print(sdf2.format(date));
Rich Seller
I'll try that, but I don't think it's going to solve the problem. In my application, I'm not actually converting back to a string. I'm saving the Date to a database, and it's wrong there, too.
Matt Ball
Are your format strings consistent? Some DBMSs will automatically convert values if they can figure things out, some won't. Are the problematic values in a column(s) with different formatting applied at the db level? Or coming from a connection that's got different parameters set?
DaveE
+8  A: 

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

Rob Di Marco
+3  A: 

The hour should be specified as HH instead of hh. Check out the section on Date and Time patterns in http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Thimmayya