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

OscarRyz picture OscarRyz · Jul 20, 2009 · Viewed 34.5k times · Source

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

Answer

Jack Leow picture Jack Leow · Jul 20, 2009

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.