Monday, September 21, 2009

SimpleDateFormat parse error - from 12pm to 12am

I got this error today, only to find out that it was a very simple code error that I overlooked.

The Error
-----------

I have a SimpleDataFormat parser to parse a date string variable to a required format:

String time = "Mon Sep 21 2009 12:56:02";
SimpleDateFormat df= new SimpleDateFormat("EEE MMM dd yyyy hh:mm:ss");
Date parsedDate = sdf.parse(time);

However, a System.out.println("parsedDate = " + df.format(parsedDate )); gives me a 00:56:02 time and not a 12:56:02 time.


Reason for error
-----------------
In the SimpleDateFormat class, formatting hour in HH will return a hour between 00-23 (i.e. in 24 hour format) while formatting hour in hh will return a hour between 01-12 (12 hour format). - a good source code to look at is http://www.java-examples.com/formatting-hour-using-simpledateformat

Ensure that your SimpleDateFormat class has been instantiated this way:
SimpleDateFormat df= new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");

No comments:

Post a Comment

Thank you for your comment.