Rafael Sedrakyan
Rafael Sedrakyan

Reputation: 2629

php regex for date and time

I need a regex for validating date and time with the following format: yyyy-mm-ddThh:mm:ss. T is just a symbol between date and time. Thanks for help

Upvotes: 0

Views: 1497

Answers (5)

J. Bruni
J. Bruni

Reputation: 20492

Fully-powered solution:

function validate($str) 
{
    preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})$/', $str, $matches);

    if (count($matches) != 7)
        return false;

    $valid_year   = range(2000, 2050); // your range
    $valid_month  = range(1, 12);
    $valid_day    = range(1, 31);
    $valid_hour   = range(0, 24);
    $valid_minute = range(0, 59);
    $valid_second = range(0, 59);

    list($str, $year, $month, $day, $hour, $minute, $second) = $matches;

    foreach(array('year', 'month', 'day', 'hour', 'minute', 'second') as $part)
    {
        if (!in_array($$part, ${'valid_'.$part}))
            return false;
    }

    return checkdate($month, $day, $year); // this will reject absurd values like February 30 or April 31
}

EDIT: I don't trust strtotime. For example: "The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC." (quoted from strtotime manual page). What if I want to accept dates out of this range? To me, strtotime is an unknown black-box. Don't get me wrong: I do use it, eventually! But I wouldn't for this case.

Upvotes: 4

Tomalak
Tomalak

Reputation: 338158

This checks if the time value represents a valid date:

$t = strtotime($yourTimeString);

if ($t === FALSE) {
  // $yourTimeString is not valid.
}

If you want to verify the string format itself, use a regex check.

Upvotes: 1

Colin O'Dell
Colin O'Dell

Reputation: 8647

^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$

This will ensure it's in the proper format. You would then need to call a function like strtotime to ensure it's a valid datetime as well.

Upvotes: 1

Ruslan Abuzant
Ruslan Abuzant

Reputation: 631

I do not think that is actually needed as people/applications might have that date string entered in different formats depending on the system's locale.

What should work best, is getting the UNIX_TIMESTAMP from the given date and check if it is a valid one.

Example:

$date1 = "2011-02-23T13:04:41";
$date2 = str_replace("T", " ", $date1); // removing the T
$date3 = strtotime($date2);

Now you just check and work with $date3.. if that's valid or meets your required criteria, then the original entered date is as well.

Just in case you do not need all this mess, go plain with:

(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})  // pseudo - not tested 

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

Try this regex, putting letter 'T' between date regex and time regex:

(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})

Upvotes: 1

Related Questions