How to check Regular Expression for Timestamp in GWT?
Solution 1
Just something simple as only describing the pattern like this:
^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}(?: [AP]M)?(?: [+-]\d{4})?$
as any tentative of real date validation with a regex sounds inherently wrong.
I got the uppercase Z as RFC822 timezone, regex needs changes to comply to TZDs or general textual time zones.
Solution 2
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
Related videos on Youtube
Comments
-
StackOverFlow over 1 year
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-DD HH:mm:ss.S Z
Where
Y: year, M: Month, D: Date, H: hour, m: minute, s: second, S: Milisecond 3 digit only, Z: Time zone.
I am getting timestamp format in string format so want to validate it.
How to check above regular expression in GWT?