0

I trying a simple exercise to converter time from 12 to 24, below my code:

 String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm:ssa")).toString();
    System.out.println("result = " + result);

The problem is when the seconds are 0 the method truncate the seconds, for example with time 12:00:00AM the result is 00:00, I want it to be 00:00:00.

Thanks.

Bkfsec
  • 327
  • 5
  • 11
  • Related: [Formatting local time in java](https://stackoverflow.com/questions/44701422/formatting-local-time-in-java) – Ole V.V. Aug 21 '18 at 09:30

1 Answers1

5

You need to specify the format:

DateTimeFormatter.ISO_TIME.format(LocalTime.of(0, 0))
// returns "00:00:00"

You can also use your own pattern. The following produces the same output:

DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalTime.of(0, 0))
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • So, I have to split the time string, and in case it is AM or PM? – Bkfsec Aug 21 '18 at 14:28
  • This format uses 24H, so AM/PM wasn't included. What do you mean by "split"? Can you give an example? – ernest_k Aug 21 '18 at 14:35
  • @Faber `LocatTime.of(0,0)` was just an example. I believe in your case you have to call `DateTimeFormatter.ISO_TIME.format(LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm:ssa")))` to get the desired output. – ernest_k Aug 21 '18 at 15:03