bhuvesh
bhuvesh

Reputation: 749

SimpleDateFormat shows time in 24-hours even after using "hh" for hour

Accoridng to SimpleDateFormat,

if i will use hh for hour, then i will get time in AM/PM, so I am trying this,

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy hh:mm:ss Z");
System.out.println(sdf.parse("Jan 30 2014 09:07:32 GMT").toString());

but the output of above parsed date is still in 24 hours format instead of 12 hours AM/PM.

if I am using hh instead of HH why my output is incorrect ? I have also tried KK already but didn't work either.

Upvotes: 0

Views: 297

Answers (2)

stevecross
stevecross

Reputation: 5684

I get Thu Jan 30 10:07:32 CET 2014. This is because Date::toString() returns the date in a localized represantation. To get the desired output, you have to use another DateFormat like this:

SimpleDateFormat dateFormatForParsing = new SimpleDateFormat("MMM dd yyyy hh:mm:ss Z");
SimpleDateFormat dateFormatForOutput = new SimpleDateFormat("ha");
Date parsedDate = dateFormatForParsing.parse("Jan 30 2014 09:07:32 GMT");

System.out.println(dateFormatForOutput.format(parsedDate));

This outputs 10AM.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502436

but the output of above parsed date is still in 24 hours format instead of 12 hours AM/PM.

You've parsed the value using hh, but the output is just what you get from calling Date.toString():

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

where:
... hh is the hour of the day (00 through 23), as two decimal digits.

The fact that you parsed using a 12-hour time of day is irrelevant to the output of Date.toString(). A Date doesn't have any clue about format, or time zone, or calendar - it's just an instant in time. (Internally, a number of milliseconds since the Unix epoch.)

If you need to convert a Date to a String in a particular format, you should use DateFormat.format to do so.

I would also strongly discourage you from using a parsing format which uses hh but without an AM/PM designator - do you really only want to be able to represent values which occur in the morning?

Are you really sure that your input data is in 12-hour format? It seems unlikely to me - in particular, when the hour is zero-padded, that usually indicates that it's in a 24-hour format. The lack of an AM/PM specifier suggests that again.

Upvotes: 4

Related Questions