0

I have faced with something I do not understand. It's trivial operation (parsing string to date) but it does not take into account AM/PM, it always set AM.

Here is my example, when I parse startDate into Date it set AM for it (I expect PM).

String startDate = "Thu Apr 02 04:50 PM 2020";
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm a yyyy");
Date date1 = sdf.parse(startDate);
System.out.println(date1.toLocaleString());

System output is

Apr 2, 2020 4:50:00 AM

What do I do wrong? Please advise.

Dmytro Pastovenskyi
  • 5,240
  • 5
  • 37
  • 56
  • I am afraid that with `SimpleDateFormat` nothing is trivial, at least not parsing. It’s a notorious troublemaker of a class. Instead I recommend you use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 17 '20 at 19:12

1 Answers1

5

You used HH which is 24 hour time (rendering the time 4 am and 4 pm). Use hh instead like,

SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd hh:mm a yyyy");

with that one change I get

Apr 2, 2020, 4:50:00 PM

You could, alternatively, alter your startDate like

String startDate = "Thu Apr 02 16:50 PM 2020";

which gives the same output (with HH).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249