Regular expression to match MySQL timestamp format "Y-M-D H:M:S"

Viewed 15999

I am trying to create a regular expression to match a string holding a date in the MySQL timestamp format, ex "2012-07-16 02:04:33".

It is not as easy as it sounds, e.g. you should not end up with February 30th.

I know there are easier ways to do this, but I am depending on being able to pass a string and a regular expression to evaluate that string.

I would be glad for any suggestions.

3 Answers

This should work for either 2019-04-30 or 2019-04-30 12:12:12

/^([1-2][0-9]{3})-([0-1][0-9])-([0-3][0-9])(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/

It also has the advantage of not validating 0000-00-00

Related