Search code examples
phpmysqlepoch

php date format inserting wrong date


I am confused as to why this piece of code does not convert a date in the UK format 00/00/0000 to mysql date format 0000-00-00. What i get in the db is 1970-01-01. It is in the date format not datetime so it should work? Thanks

$destroy = mysql_real_escape_string($_POST['destroy']);
$desttempdate=str_replace("-", "/", $destroy); 
$destdate = date('Y-m-d', strtotime($desttempdate));

Solution

  • Here are a few options for you to get it working:

    Something like this for PHP4:

    function date2timestamp($date,$seperator='/'){
        if($date!=''){
            $dateEx = explode($seperator,$date);
            $date = (strlen($dateEx[2])==2?'20'.$dateEx[2]:$dateEx[2]).'-'.$dateEx[1].'-'.$dateEx[0].' 00:00:00';
        }
        return $date;
    }
    

    For PHP5.3 use createFromFormat():

    $date = DateTime::createFromFormat('j/M/Y', $UK_date);
    echo $date->format('Y-m-d');
    

    Also other options for createFromFormat() in PHP5.2 include: