[英]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.我希望从 1 到 9 的小时没有前导零,但分钟有零,同时还增加了 15 分钟的时间。 Right now, when I input 1 and 46 i get 02:01, and i want to get 2:01
现在,当我输入 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);
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您可以使用格式为“H:mm”的DateTimeFormatter https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.ZFC35FDC70D52C79
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.
数字:如果字母数为 1,则值为 output,使用最小位数且无填充。 Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.
否则,位数将用作 output 字段的宽度,必要时将值补零。 The following pattern letters have constraints on the count of letters.
以下模式字母对字母数量有限制。 Only one letter of 'c' and 'F' can be specified.
只能指定一个字母“c”和“F”。 Up to two letters of 'd', 'H', 'h', 'K', 'k', 'm', and 's' can be specified.
最多可以指定两个字母“d”、“H”、“h”、“K”、“k”、“m”和“s”。 Up to three letters of 'D' can be specified.
最多可以指定三个字母“D”。
When you print time
directly, it uses the toString()
method of LocalTime
, which is documented as:当您直接打印
time
,它使用LocalTime
的toString()
方法,该方法记录为:
The output will be one of the following ISO-8601 formats:
output 将是以下 ISO-8601 格式之一:
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.由于您希望小时不以零为前缀,因此您需要自己指定格式,方法是调用
format(...)
方法而不是toString()
方法。
Eg例如
System.out.println(time.format(DateTimeFormatter.ofPattern("H:mm")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.