user2731629 user2731629 - 1 year ago 75
Java Question

Convert String (hhmmss) to Date (hh:mm) in Java

My Input String is like '2017-04-11-135352' in format (

) and I want to convert it to April 11, 2017 1:53 PM

I dont have any issues converting the yyyy-mm-dd, All I need is the best approach to convert the last part.
hh:mm a

Answer Source

Some mistakes you made that get your String not parseable, in fact you ask to parse 13 as a clock-hour-of-am-pm (1-12) but you can't, and you use same mm for minute and for month

  • m is for minute-of-hour
  • M if for month-of-year
  • h is for clock-hour-of-am-pm (1-12)
  • H if for hour-of-day (0-23)

So ti fix :

String str = "2017-04-11-135352";
DateTimeFormatter from = DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss");
LocalDateTime date = LocalDateTime.parse(str,from);

String text = date.format(DateTimeFormatter.ofPattern("MMM dd,yyyy hh:mm a"));
System.out.println(text); // avr, 11,2017 01:53 PM
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download