preg_match date time validation

While developing a custom module, I needed to validate the following date time format:

1987-11-22T23:52:12

The following code was used to create a pattern for the preg_match and to test the results. (Can be used as is.)

$pattern  = '/^([1-2][0-9]{3})-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])T([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';
$datetime = '2901-01-31T22:58:45';

$matches = array();

$res = preg_match($pattern, $datetime, $matches);

echo 'Matched: '.$res.PHP_EOL;

for ($i = 0; $i < count($matches); $i++)
{
  echo 'Match '.$i.': '.$matches[$i].PHP_EOL;
}

Explanation:

The first four digit (year) should start with either 1 or 2, followed by any three digits within the range 0-9.

Dash follows.

The next set of two digits (month), should start with either 0 or 1, followed followed by any three digits within the range 0-9.

Dash follows.

The next set of two digits (day), should either
Start with a digit within the range of 0-2 followed by a digit within the range of 0-9, or 

start with the digit 3 followed by a digit within the range of 0-1

Letter 'T' follows.

The next set of two digits (hour), should start with either the digits 0 or 1, followed by any digit within the range 0-9, or the digit 2, followed by any digit within the range 0-3

':' follows

The next set of two digits (minutes), should start with a digit within the range of 0-5, followed by any digit within the range of 0-9

':' follows

The next set of two digits (seconds), should start with a digit within the range of 0-5, followed by any digit within the range of 0-9

Tags: 
PHP / MySQL

Recent Comments

Forward by Dries Buytaert, Founder and Project Lead, Drupal; CTO Acquia.

Order now from:

Managing Expectations Podcast with DrupalEasy

Author Interview http://tinyurl.com/8a8nxno

We provide the most Shiny Drupal Bits & Pixels

Since Drupal 4.x