我有两个时间字符串,它们可以采用任何格式(12小时或24小时,带有或不带有时区)。如果它们的格式在Java中不同,并且数据不匹配,该如何比较?
PS]我准备了一个正则表达式列表,并使用这些表达式匹配字符串以获取格式,然后使用字符串的equals()方法检查数据差异。这种方法的问题是(20:01:02,20 01 01)返回格式差异,而预期结果应该是数据差异。请帮助,我在这里呆了很长时间。
正则表达式的映射-
private static final Map<String, String> TIME_FORMAT_REGEXPS = new HashMap<String, String>() {{
put("^(1[0-2]|0?[1-9]):([0-5]?[0-9])(●?[AP]M)?$", "1");
put("^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$", "2");
put("^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])(●?[AP]M)?$", "3");
put("^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$", "4");
put("^(2[0-3]|[01][0-9]):?([0-5][0-9])$", "5");
put("^(?<hour>2[0-3]|[01][0-9]):?(?<minute>[0-5][0-9])$", "6");
put("^(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])$", "7");
put("^(?<hour>2[0-3]|[01][0-9]):?(?<minute>[0-5][0-9]):?(?<second>[0-5][0-9])$", "8");
put("^(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$", "9");
put("^(2[0-3]|[01][0-9]):?([0-5][0-9]):?([0-5][0-9])(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$", "10");
put("^(?<hour>2[0-3]|[01][0-9]):?(?<minute>[0-5][0-9]):?(?<second>[0-5][0-9])(?<timezone>Z|[+-]"
+ "(?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$",
"11");
}};
检查字符串格式的功能-
private String determineTimeFormat(String dateString) {
for (String regexp : TIME_FORMAT_REGEXPS.keySet()) {
if (dateString.toLowerCase().matches(regexp)) {
return TIME_FORMAT_REGEXPS.get(regexp);
}
}
return "100"; // Unknown format.
}
您可以尝试这样的事情:
// create a formatter
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd/MM/yyyy HH:mm:ss]") // Add as many optional patterns as required
.appendPattern("[dd-MM-yyyy HH:mm:ss]")
.appendPattern("[dd-MM-yyyy[ [HH[:mm][:ss]]]]") // nested optional tokens specified with square brackets []
.appendOptional(DateTimeFormatter.ISO_DATE_TIME) // can use standard Java DateTimeFormatters as well
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0) // supply default values for missing fields
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
// each of these will parse successfully
LocalDateTime time1 = LocalDateTime.parse("2020-02-01T01:02:00+00:00", formatter);
LocalDateTime time2 = LocalDateTime.parse("01-02-2020 01:02:00", formatter);
LocalDateTime time3 = LocalDateTime.parse("01-02-2020 01:02", formatter);
LocalDateTime time4 = LocalDateTime.parse("01-02-2020", formatter);
// use .equals() method to compare times
assert time1.equals(time2); // true
assert time2.equals(time3); // true
assert time3.equals(time4); // true
此相关答案的帮助https://stackoverflow.com/a/39685202/7174786
有关其他DateTimeFormatter
的详细信息,请参见JavaDocs:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html