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