I’m trying to write a regular expression, for use in a javascript function, to test datetimes.
I’m wanting to allow dates in the following formats only:
YYYY-MM-DD HH:mm:ss
YYYY-MM-DDTHH:mm:ss
YYYY-MM-DD HH:mm
YYYY-MM-DDTHH:mm
This is as far as I’ve managed to get so far:
/^(19[0-9]{2}|2[0-9]{3})-(0[1-9]|1[012])-([123]0|[012][1-9]|31)[ \/T\/t]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/
It does what I want except requires hours, minutes and seconds rather than hours and minutes with seconds optional.
Thanks for your help!
I’ve written a small jsFiddle with some test data to make your lives easier. Just update the pattern variable and run it and the table should match up.
UPDATE: I updated this answer to change (…) to (?:…) so your capturing won’t be messed up.
Try this:
Updated fiddle:
http://jsfiddle.net/smMJC/5/
What I did was changing
to:
which means making that part optional. (The double colon is intentional because it is a
(?: ... )?non capturing group outside and a literal “:” inside.Also, you may want to change:
to:
unless you really want to match strings like:
with a slash instead of T – compare those two demos: