Web*_*ory -1 java datetime time-format
我的解析器可能会遇到“2:37PM”(由“H:mma”解析)或“02:37PM”(由“hh:mma”解析)。如何在不使用 try-catch 的情况下解析两者?
当我出错时,我会收到这样的错误:
发现冲突:字段 AmPmOfDay 0 与源自 02:37 的 AmPmOfDay 1 不同
首先,您收到的错误是由模式中的 引起的,该模式以 24 小时格式解析小时,如果您在模式末尾H
添加 (AM/PM),则会遇到麻烦。a
您可以使用考虑两种模式的a 将 sjava.time
解析String
为LocalTime
s :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));
}
Run Code Online (Sandbox Code Playgroud)
这个的输出是
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));
}
Run Code Online (Sandbox Code Playgroud)
但事实证明,您只需要一种模式(无论如何,这比两种模式更好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));
}
Run Code Online (Sandbox Code Playgroud)