java如何识别字符串里的多种时间格式的字符串
时间: 2023-08-11 15:05:34 浏览: 123
要识别字符串中的多种时间格式,你可以使用 `DateTimeFormatter` 类的 `parseBest` 方法。该方法可以尝试使用多个模式来解析时间字符串,返回最匹配的结果。
以下是一个示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
public class TimeRecognition {
public static void main(String[] args) {
String input = "The time is 12:34:56";
List<String> patterns = new ArrayList<>();
patterns.add("HH:mm:ss");
patterns.add("hh:mm:ss a");
patterns.add("h:mm:ss a");
LocalDateTime time = null;
for (String pattern : patterns) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
time = LocalDateTime.parse(input, formatter);
break;
} catch (DateTimeParseException e) {
// 当前模式不匹配,尝试下一个模式
}
}
if (time != null) {
System.out.println("Parsed time: " + time);
} else {
System.out.println("No time found");
}
}
}
```
在上述示例中,我们尝试使用多个时间格式模式来解析输入字符串。如果找到匹配的模式,则将其解析为 `LocalDateTime` 对象,并输出解析结果。如果没有找到匹配的模式,则输出 "No time found"。
你可以根据需要添加更多的时间格式模式到 `patterns` 列表中,并根据你的实际需求进行调整。