akhil agrawal
akhil agrawal

Reputation: 1

compare format of time string in java

I have two time strings that can be in any format(12 hours or 24 hours, with or without timezone). How do I compare if their format is different in java and if data mismatch is there?

PS> I have prepared a list of regex expressions and matching string with those expressions to get the format, then checking for data differences using equals() method of string. problem with this approach is (20:01:02,20 01 01) return format difference whereas the expected result should be data difference. Please help, I am stuck here for a long time.

map of regex expressions-

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");

}};

function to check format of string-

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.
}

Upvotes: 0

Views: 249

Answers (1)

Alessandro Scarlatti
Alessandro Scarlatti

Reputation: 734

You can try something like this:

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

Assistance from this related answer https://stackoverflow.com/a/39685202/7174786

See the JavaDocs for additional DateTimeFormatter details: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Upvotes: 1

Related Questions