Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
TronCraze Avatar asked Apr 22 '26 03:04

TronCraze


1 Answers

[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

like image 97
sebilasse Avatar answered Apr 24 '26 17:04

sebilasse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!