Search code examples
phpmysqldatetimedate-arithmetic

DateTime Calculation Standardize


Is there any ways to standardize the date time format? Currently I am grabbing a data from database and they have sort my datetime into this format 2013-09-01 17:51:00 while the datetime calculation I grab are in this format 2013-9-3---02:18 Even that I might able to remove the --- for the 2nd datetime but the format seem to be different from the first 1 and I guess that the reason I unable to perform the difference date time calculation.

Is there any recommendation or best way to convert or change the new grabbed datetime standardize exactly same as the first 1 so that I can perform some comparison before inserting into database?

Besides, I would like to calculate the difference between 2 datetime. I saw quite a lot of example online but most of it are calculating the date instead of date time ~ Any one guide me?


Solution

  • Try this

    $date = '2013-9-3---02:18';
    $newdate = str_replace('---',' ',$date);
    $phpdate = strtotime($newdate);
    echo $mydate = date( 'Y-m-d H:i:s', $phpdate );
    echo "<br>";
    echo $mysqldate = '2013-09-01 17:51:00';
    echo "<br>";
    $datetime1 = new DateTime($mydate);
    $datetime2 = new DateTime($mysqldate);
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%Y-%m-%d %H:%i:%s');
    

    Output

    2013-09-03 02:18:00
    2013-09-01 17:51:00 
    
    00-0-1 08:27:0