Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to validate a timestamp

I need a regular expression to validate a timestamp of the format, using Javascript:

YYYY/MM/DD HH:MI:SS

I tried cooking up a few, but seems my regex skills fail to cover something or other.

Please give me a reference or way to do it.

P.S. : I mention regex, only as a suggestion. Im using Javascript and welcome any alternative.

like image 949
M.N Avatar asked Jun 29 '09 10:06

M.N


People also ask

What is the regular expression for date format?

To match a date in mm/dd/yyyy format, rearrange the regular expression to ^(0[1-9]|1[012])[- /.] (0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d$. For dd-mm-yyyy format, use ^(0[1-9]|[12][0-9]|3[01])[- /.]

What is a timestamp format?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


2 Answers

I would recommend to use Datejs for this. Parsing the date yourself is not necessary and a Regex is not enough to validate a timestamp. With datejs you could parse the string in a date and you'll get null if its invalid:

Date.parse("2009/06/29 13:30:10", "yyyy/MM/dd HH:mm:ss");
like image 156
Tim Büthe Avatar answered Nov 04 '22 20:11

Tim Büthe


If you just want to validate the syntax, here is the POSIX regex:

[0-9]{1,4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}

But if you want to check the semantics, I would process the string using your language of choice, there are too many cases you cannot cover with regular expressions (like leap years/seconds, daylight savings, etc)

like image 40
soulmerge Avatar answered Nov 04 '22 20:11

soulmerge