如何用Java解析1或2位数的小时字符串? [英] How to parse a 1 or 2 digit hour string with Java?
问题描述
我的解析器可能遇到"2:37 PM"(由"H:mma"解析)或"02:37 PM"(由"hh:mma"解析).如何在不借助try-catch的情况下解析两者?
My parser may encounter "2:37PM" (parsed by "H:mma") or "02:37PM" (parsed by "hh:mma"). How can I parse both without resorting to a try-catch?
如果我弄错了,我会收到这样的错误:
I receive an error like this when I get it wrong:
发现冲突:字段AmPmOfDay 0与派生的AmPmOfDay 1不同从02:37
Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 02:37
推荐答案
首先,您收到的错误是由模式中的 H
引起的,它以24小时格式解析小时,如果在模式末尾放置 a
(用于AM/PM),则会遇到麻烦.
First of all, the error you get is caused by the H
in your pattern, which parses hours in 24-hour format and gets into trouble if you put an a
(for AM/PM) at the end of the pattern.
您可以使用考虑了 DateTimeFormatter
的 java.time
将 String
解析为 LocalTime
两种模式:
You can use java.time
to parse the String
s to LocalTime
s using a DateTimeFormatter
that considers both of the patterns:
public static void main(String[] args) {
// define a formatter that considers two patterns
DateTimeFormatter parser = DateTimeFormatter.ofPattern("[h:mma][hh:mma]");
// provide example time strings
String firstTime = "2:37PM";
String secondTime = "02:37PM";
// parse them both using the formatter defined above
LocalTime firstLocalTime = LocalTime.parse(firstTime, parser);
LocalTime secondLocalTime = LocalTime.parse(secondTime, parser);
// print the results
System.out.println("First:\t" + firstLocalTime.format(DateTimeFormatter.ISO_TIME));
System.out.println("Second:\t" + secondLocalTime.format(DateTimeFormatter.ISO_TIME));
}
它的输出是
First: 14:37:00
Second: 14:37:00
但是事实证明,您只需要一种模式(总之,在 DateTimeFormatter
中要比两个模式更好),因为 h
可以解析一个小时或一个小时的时间.两位数.因此,以下代码将产生与上面完全相同的输出:
But it turned out you only need one pattern (which is better to have than two in a DateTimeFormatter
anyway) because the h
is able to parse hours of one or two digits. So the following code produces exactly the same output as the one above:
public static void main(String[] args) {
// define a formatter that considers hours consisting of one or two digits plus AM/PM
DateTimeFormatter parser = DateTimeFormatter.ofPattern("h:mma");
// provide example time strings
String firstTime = "2:37PM";
String secondTime = "02:37PM";
// parse them both using the formatter defined above
LocalTime firstLocalTime = LocalTime.parse(firstTime, parser);
LocalTime secondLocalTime = LocalTime.parse(secondTime, parser);
// print the results
System.out.println("First:\t" + firstLocalTime.format(DateTimeFormatter.ISO_TIME));
System.out.println("Second:\t" + secondLocalTime.format(DateTimeFormatter.ISO_TIME));
}
这篇关于如何用Java解析1或2位数的小时字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!