Regular expression to match MySQL timestamp format "YMD H: M: S"

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

It is not as simple as it seems. you should not end on February 30th.

I know that there are simpler ways to do this, but I depending on the ability to pass a string and a regular expression to evaluate this string.

I would be happy for any suggestions.

+6
source share
3 answers

Regular expression:

/^(((\d{4})(-)(0[13578]|10|12)(-)(0[1-9]|[12][0-9]|3[01]))|((\d{4})(-)(0[469]|1‌​1)(-)([0][1-9]|[12][0-9]|30))|((\d{4})(-)(02)(-)(0[1-9]|1[0-9]|2[0-8]))|(([02468]‌​[048]00)(-)(02)(-)(29))|(([13579][26]00)(-)(02)(-)(29))|(([0-9][0-9][0][48])(-)(0‌​2)(-)(29))|(([0-9][0-9][2468][048])(-)(02)(-)(29))|(([0-9][0-9][13579][26])(-)(02‌​)(-)(29)))(\s([0-1][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9]))$/

performs this work. Thanks for the input.

+14
source

You have to do it in 2 steps, instead of trying to use really complex regular expressions.

1: . -

/^\d\d\d\d-(\d)?\d-(\d)?\d \d\d:\d\d:\d\d$/g

2: , - strtotime() PHP ( , ) , , , , 30 .

+8

This should work for 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 that it does not check 0000-00-00

0
source

All Articles