简体   繁体   中英

How to remove leading zero from time(hours)

I want to have the hour from 1-9 without the leading zero, but the minutes with the zero while also adding 15 minutes to the time. Right now, when I input 1 and 46 i get 02:01, and i want to get 2:01

Scanner scan = new Scanner(System.in);
int hour = scan.nextInt();
int minutes = scan.nextInt();
LocalTime time = LocalTime.of(hour , minutes);
time = time.plusMinutes(15);
System.out.println(time);

You can use DateTimeFormatter with format "H:mm" https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html

DateTimeFormatter.ofPattern("H:mm").format(LocalTime.now())

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.

When you print time directly, it uses the toString() method of LocalTime , which is documented as:

The output will be one of the following ISO-8601 formats:

  • HH:mm
  • HH:mm:ss
  • HH:mm:ss.SSS
  • HH:mm:ss.SSSSSS
  • HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

Since you want the hour to not be zero-prefixed, you need to specify the format yourself, by calling the format(...) method instead of the toString() method.

Eg

System.out.println(time.format(DateTimeFormatter.ofPattern("H:mm")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM