如何从时间(小时)中删除前导零

How to remove leading zero from time(hours)

我想要从 1-9 开始的小时没有前导零,但是分钟有零,同时还要增加 15 分钟。 现在,当我输入 1 和 46 时,我得到 02:01,我想得到 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);

您可以使用 DateTimeFormatter 格式 "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.

当你直接打印 time 时,它使用 toString() method of LocalTime,记录为:

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.

由于您希望小时不以零为前缀,因此您需要自己指定格式,方法是调用 format(...) 方法而不是 toString() 方法。

例如

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