我正在尝试创建 Java 类 LocalTime
的对象,如下所示:
LocalTime beginning = LocalTime.of(int hours, int minutes);
我的问题是我希望我的用户可以按以下格式输入时间:HH:MM 但是,当输入像 14:00 这样的字符串时,我会将“:”替换为“”。
然后我说:
hours = Integer.parseInt(eingabe.substring(0, 2));
minutes = Integer.parseInt(eingabe.substring(2));
但是现在分钟是 0,而不是我想要的 00。
我做了一些研究,发现了类似 String.format("%02d", 分钟)
的东西,但是 LocalTime.of()
的参数需要是整数。
最佳答案
如果您有类似 14:00
的输入您不需要手动格式化,而是可以使用 java.time.format.DateTimeFormatter
:
String input = "14:00";
DateTimeFormatter simpleTime = DateTimeFormatter.ofPattern("HH:mm");
LocalTime localtime = LocalTime.parse(input, simpleTime);
但是,您原来的问题一开始就不是问题。 “14:00”中的“00”只是格式化,并不代表分钟的整数值为00
:是0
;它只是显示为“00”,以减少查看时间的人们的困惑(例如,很难区分 14:1
和 14:10
等)。
关于java - LocalTime 对象 - 在分钟中添加前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41921297/