0

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.
}
  • Share your tries please, edit your post and add your cpde – azro May 25 '20 at 10:13
  • Please add what you did? some code of your question – Deep Dalsania May 25 '20 at 10:14
  • It seems this question needs to be more focused – Nowhere Man May 25 '20 at 10:15
  • edited how can i change closed to open? – akhil agrawal May 25 '20 at 10:24
  • @Joe (and others) you close-voted this question only 6(!) minutes after it was asked??? This seems inappropriate to me. – isnot2bad May 25 '20 at 10:25
  • @akhilagrawal you can't. Three votes are needed to open a closed question. You don't have sufficient priviledges yet, to vote for reopening. – isnot2bad May 25 '20 at 10:29
  • 1
    Once you’ve determined the format of a string, parse it into a `LocalTime` object using an appropriate `DateTimeFormatter` for that format. Then compare the two obtained `LocalTime` objects for equality. Use your search engine for the details. (You may also use the formatters for determining the format and skip the regex.) – Ole V.V. May 25 '20 at 16:51
  • 1
    Under what circumstances would you consider that two times are the same time if one has UTC offset and the other one hasn’t? And if they have different offsets? – Ole V.V. May 25 '20 at 16:54
  • @OleV.V. i got your point. Just one doubt ,how can i use formatter for determining the format .I dont think the LocalDateTime object has a pattern which is also stated in this link:https://stackoverflow.com/questions/57622410/java-is-there-a-way-to-get-pattern-of-a-given-date-string-or-from-a-localdate. Please confirm.Basically i was thinking on alternatives of skipping regexes. – akhil agrawal May 29 '20 at 08:38

1 Answers1

1

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