Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent date parsing using SimpleDateFormat

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 :)

like image 464
Matt Ball Avatar asked Aug 21 '09 17:08

Matt Ball


Video Answer


3 Answers

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

like image 128
Rob Di Marco Avatar answered Sep 30 '22 12:09

Rob Di Marco


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

like image 23
Thimmayya Avatar answered Sep 30 '22 13:09

Thimmayya


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));
like image 24
Rich Seller Avatar answered Sep 30 '22 13:09

Rich Seller