Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa")
return 11 a.m.?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With