-1

I am using HH:mm format to print the hour and minute in java. It will give the time in format 05:12, 00:04. But my requirement is to get with single digit hours:

05:12 => 5:12
00:04 => 0:04  
10:18 => 10:18

Below i have the code which i am running to produce the date,

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TestDateUtil {

    public static void main(String ar[]) {
        LocalTime time = LocalTime.now();
        String t = time.format(DateTimeFormatter.ofPattern("HH:mm"));
        System.out.println(t);  

    }
} 

I know that i can use string operations to make the time split on the basis of : and then change that, but that too need a lot more variations of conditions checking which i don't want to do. Is there any way of doing it?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Mandrek
  • 1,159
  • 6
  • 25
  • 55

2 Answers2

6

The docs for DateTimeFormatter say:

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary. The following pattern letters have constraints on the count of letters. Only one letter of 'c' and 'F' can be specified. Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified. Up to three letters of 'D' can be specified.

So simply change your pattern from HH:mm to H:mm.

QBrute
  • 4,405
  • 6
  • 34
  • 40
0
DateTimeFormatter.ofPattern("H:mm").format(LocalTime.now())
Leketo
  • 133
  • 1
  • 8