Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 270
OscarRyz Avatar asked Jul 20 '09 17:07

OscarRyz


People also ask

What timezone does SimpleDateFormat use?

Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy , derived from this milliseconds value.

What is the use of SimpleDateFormat in Java?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

What is parse in SimpleDateFormat parse do?

The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.

What is HH date format?

The hour, using a 12-hour clock from 01 to 12. More information: The "hh" Custom Format Specifier. The hour, using a 24-hour clock from 0 to 23. More information: The "H" Custom Format Specifier.


2 Answers

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.

like image 157
Jack Leow Avatar answered Nov 16 '22 03:11

Jack Leow


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
like image 31
Steve McLeod Avatar answered Nov 16 '22 03:11

Steve McLeod