TronCraze
TronCraze

Reputation: 295

Check PHP datetime stamp is correct?

Is there a way of checking whether a date time stamp is correct in PHP?

I am currently using yyyy-mm-dd hh:mm:ss in MySQL and would like to ensure when a user provides the date/time stamp in a form it matches the correct format.

Upvotes: 3

Views: 5992

Answers (4)

user3342806
user3342806

Reputation: 11

This a duplicate question. For additiona discussion and answers see MySQL: How to check if a string is a valid DATE, TIME or DATETIME

Upvotes: 1

sebilasse
sebilasse

Reputation: 4618

[until someone comes with good (bugfree), working checkdate() example ] I am using this function:

<?php 
function validateMysqlDate( $date ){ 
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $date, $matches)) { 
        if (checkdate($matches[2], $matches[3], $matches[1])) { 
            return true; 
        } 
    } 
    return false; 
} 

// check it: 
  $a = validateMysqlDate('2012-12-09 09:04:00');
  $b = validateMysqlDate('20122-12-09 09:04:00');
  $c = validateMysqlDate('2012-12_09 09:04:00');
  $d = validateMysqlDate('');
  var_dump( $a );
  var_dump( $b );
  var_dump( $c );
  var_dump( $d ); 
?>

and btw: checkdate() would return true for $b although it is not a valid mysql datetime

Upvotes: 6

Robin
Robin

Reputation: 4260

Try to parse the given string and then check it is the same date that you entered, note the below:

$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2011-01-32 12:00:00');
echo $dt->format('Y-m-d H:i:s');
// outputs 2011-02-01 12:00:00

HTH.

Upvotes: 0

Ben Swinburne
Ben Swinburne

Reputation: 26467

You can use the checkdate() function to check the validity of a date.

http://php.net/manual/en/function.checkdate.php

You can also pass all of the parts of your timestamp to mktime() and if false or -1 is returned (depending on PHP version) then it's an invalid date

http://www.php.net/manual/en/function.mktime.php

Upvotes: 1

Related Questions