SimpleDateFormat does not handle 12 m correctly.

I am trying to parse the string "2/20/2012 12:00:00 AM" using SimpleDateFormat , and it seems to be "2/20/2012 12:00:00 AM" out 12 noon. instead of this.

  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 get the last one out. Is there something wrong with my format string?

(And please, no one says "use JodaTime".)

+4
source share
1 answer

Use this instead:

 new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa") 

Note. I use hh instead of hh . The first one does this:

Hour at am / pm (1-12)

hh does the following:

Hour a day (0-23)


You tell SimpleDateFormat that you will go through an hour in the range of 0-23, but in fact you do not. That is why you get this problem.

+12
source

Source: https://habr.com/ru/post/1491985/


All Articles