0

我有两个可以采用任何格式的时间字符串(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.
}
4

1 回答 1

1

你可以尝试这样的事情:

// 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

于 2020-05-27T02:22:47.637 回答