我的解析器可能会遇到“2:37PM”(由“H:mma”解析)或“02:37PM”(由“hh:mma”解析)。如何在不使用 try-catch 的情况下解析两者?
当我出错时,我会收到这样的错误:
发现冲突:AmPmOfDay 0 字段与派生的 AmPmOfDay 1 字段不同
从 02:37 开始
首先,您收到的错误是由以下原因引起的H
在你的模式中,它以 24 小时格式解析小时,如果你输入一个,就会遇到麻烦a
(对于 AM/PM)位于模式的末尾。
您可以使用java.time
来解析String
s to LocalTime
使用一个DateTimeFormatter
考虑这两种模式:
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
能够解析一位或两位数字的小时数。因此,以下代码产生的输出与上面的输出完全相同:
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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)