I'm trying to parse the string "2/20/2012 12:00:00 AM"
using SimpleDateFormat
, and it seems to be coming out 12 p.m. instead.
Date fromFmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aa")
.parse("2/20/2012 12:00:00 AM");
// Calendar months are 0-indexed
Date fromCal = new Date(new GregorianCalendar(2012, 1, 20, 0, 0, 0)
.getTimeInMillis());
System.out.println(fromFmt);
System.out.println(fromCal);
outputs:
Mon Feb 20 12:00:00 PST 2012
Mon Feb 20 00:00:00 PST 2012
I would expect both of them to output the latter. Is there something wrong with my format string?
(And please nobody say 'use JodaTime'.)
Use this instead:
new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa")
Notice I'm using hh
instead of HH
. The former does this:
Hour in am/pm (1-12)
HH
does this:
Hour in day (0-23)
You're telling the SimpleDateFormat
that you're going to pass in an hour in the 0-23 range, but you're not actually doing that. That's why you get this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With