Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

this will work for you

$phpdate = strtotime( $yourdate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );

just try above example.

and if you still not able to get your date. then you have to split date and time with '-' and reformat again.

This should work :

Code:

$dateF = '2013-09-01 17:51:00';
$dateT = '2013-9-3---02:18';

$dtF = new DateTime($dateF);
$dtT = DateTime::createFromFormat('Y n j H:i', str_replace('-', ' ', $dateT));

Both dates are now in DateTime object, so now you can do anything with them :

Difference example :

$diff = $dtF->diff($dtT);
print_r($diff);
/*
    DateInterval Object
    (
        [y] => 0
        [m] => 0
        [d] => 1
        [h] => 8
        [i] => 27
        [s] => 0
        [invert] => 0
        [days] => 1
    )
*/

Compare example :

if ($dtF > $dtT) {
    echo 'Datetime in variable $dtF is bigger than $dtT';
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top