What will be the regular expression for following Timestamp format
YYYY-MM-DD HH:mm:ss.S
YYYY-MM-DD HH:mm:ss.S AM/PM
YYYY-MM-DD HH:mm:ss.S AM/PM Z
YYYY-MM
Apart from Datejs
which relays on js to check a date-string, Gwt comes with DateTimeFormat to parse date-string and format dates with support for locales. It raises a IllegalArgumentException
in the case the parsed string doesn't match the expected format .
String dateStr = "2011-04-21 20:37:36.999 -0800";
String fmt = "yyyy-MM-dd HH:mm:ss.S Z"; // your 4th case: YYYY-MM-DD HH:mm:ss.S Z
DateTimeFormat format = DateTimeFormat.getFormat(fmt);
try {
Date date = format.parse(dateStr);
System.out.println("Validated: " + date);
} catch (IllegalArgumentException e) {
System.out.println("Validation error: " + e.getMessage());
}
dateStr = "2011-04-21 08:37:36.999 PM -0800"; // your 3rd case YYYY-MM-DD HH:mm:ss.S AM/PM Z
fmt = "yyyy-MM-dd hh:mm:ss.S a Z";
format = DateTimeFormat.getFormat(fmt);
try {
Date date = format.parse(dateStr);
System.out.println("Validated: " + date);
} catch (IllegalArgumentException e) {
System.out.println("Validation error: " + e.getMessage());
}
You dont say whether the format string is fixed or it can be provided in runtime before performing the validation. So in the second case you need to use replace
to change 'Y' by 'y', and 'AM/PM' to 'a' which are the symbols used in DateTimeFormat