php - Regex matching a date and time -


i'm trying match specific datetime format in php's regex:

dd-mm-yyyy hh:ii:ss 

it should in format. meaning example when first day of month there must leading zero. e.g.:

01-01-2013 01:01:01 

i tried following pattern:

^[0-12]{2}-[0-31]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$ 

but above pattern fails on timestamps like: 09-05-2013 19:45:10.

http://rubular.com/r/egbahwincr

i understand may not correct approach validate date time this, want know wrong above.

the problem when checking "ranges", example [0-12] @ beginning. character class, , telling regex match 0 through 1, , 2. if added more numbers in after 1st one, isn't working expecting. changing regex (focused on [0-12] initial), [0-319]{2}-[0-12]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$, match 09-01-2011 11:11:10.

ensuring there valid numbers each of spaces requires little thinking outside box. regex:

(0[1-9]|[12][\d]|3[0-2])-(0[1-9]|1[0-2])-[\d]{4} (0[1-9]|1[\d]|2[0-3]):(0[1-9]|[1-5][\d]):(0[1-9]|[1-5][\d])$

will work expecting regex attempted.

if break down smaller pieces makes sense (it looks scary @ beginning). looking @ first piece (0-31 "days").

(0[1-9]|[12][\d]|3[0-2])

this using or handle 3 different cases.

  1. 0[1-9] - 0 followed number between 1-9. don't want [0-9]{2} since allow numbers 00. number valid if starts 0 , has other number after (for single digit days).
  2. [12][\d] - 1 or 2 followed digit. allows numbers 10-29 valid.
  3. 3[0-2] - 3 followed 0 through 2 matching 30, 31, , 32.

broken down, it's not bad pattern carried out each "field" in date. regex validates on each field being valid... better way confirm valid dates maybe needed. this doesn't complexity of checking if can have 30-02 example, february doesn't have 30 days.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -