Question

Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa") return 11 a.m.?

Was it helpful?

Solution

You should be getting an exception, since "23:00 PM" is not a valid string, but Java's date/time facility is lenient by default, when handling date parsing.

The logic is that 23:00 PM is 12 hours after 11:00 PM, which is 11:00 AM the following day. You'll also see things like "April 31" being parsed as "May 1" (one day after April 30).

If you don't want this behavior, set the lenient property to false on your SimpleDateFormat using DateFormat#setLenient(boolean), and you'll get an exception when passing in invalid date/times.

OTHER TIPS

You want "HH:mm aa" as your format, if you will be parsing 24-hour time.

public static void main(String[] args) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("HH:mm aa");
    final Date date = df.parse("23:00 PM");
    System.out.println("date = " + df.format(date));
}

outputs

date = 23:00 PM

Have you tried HH:mm aa?

HH is for 24 hour while hh is for 12.

Here are the formatting options specifed in the javadoc

H     Hour in day (0-23)    
k   Hour in day (1-24)  
K   Hour in am/pm (0-11)    
h   Hour in am/pm (1-12) 

Notice that "h" would be for hours 1-12. If you want to handle 1-24, try "k". for 0-23 try "H". But I would not expect valid results if you are putting in impossible data.

23:00 PM could be thought of as 11 AM the next day. Javascript and PHP work like this pretty much but I can't speak for Java.

I would guess that it does something like:

hours = hours % 12;

to ensure that the hours are in the proper range.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top