Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat not properly handling 12 a.m

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'.)

like image 897
David Moles Avatar asked Jul 17 '13 23:07

David Moles


1 Answers

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.

like image 62
Daniel Kaplan Avatar answered Oct 14 '22 20:10

Daniel Kaplan