What is the regex pattern for datetime (2008-09-01 12:35:45 )?
Solution 1:
@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.
It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:
(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})
If you're using perl, then you can get the values out with something like this:
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$minute = $5;
$second = $6;
Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.
Solution 2:
A simple version that will work for the format mentioned, but not all the others as per @Espos:
(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})
Solution 3:
http://regexlib.com/REDetails.aspx?regexp_id=610
^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$
This RE validates both dates and/or times patterns. Days in Feb. are also validated for Leap years. Dates: in dd/mm/yyyy or d/m/yy format between 1/1/1600 - 31/12/9999. Leading zeroes are optional. Date separators can be either matching dashes(-), slashes(/) or periods(.) Times: in the hh:MM:ss AM/PM 12 hour format (12:00 AM - 11:59:59 PM) or hh:MM:ss military time format (00:00:00 - 23:59:59). The 12 hour time format: 1) may have a leading zero for the hour. 2) Minutes and seconds are optional for the 12 hour format 3) AM or PM is required and case sensitive. Military time 1) must have a leading zero for all hours less than 10. 2) Minutes are manditory. 3) seconds are optional. Datetimes: combination of the above formats. A date first then a time separated by a space. ex) dd/mm/yyyy hh:MM:ss
Edit: Make sure you copy the RegEx from the regexlib.com website as StackOverflow sometimes removes/destroys special chars.
Solution 4:
$date = "2014-04-01 12:00:00";
preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date, $matches);
print_r($matches);
$matches will be:
Array (
[0] => 2014-04-01 12:00:00
[1] => 2014
[2] => 04
[3] => 01
[4] => 12
[5] => 00
[6] => 00
)
An easy way to break up a datetime formated string.