简体   繁体   中英

How to find difference between two dates

$start = "2015-01-01 10:00:00";

$end = "2015-05-05 12:06:06";


$x = strtotime($start);

$y = strtotime($end);

$z = abs($y - $x);

$days = floor($z / (60 * 60 * 24));
$years = floor($z / (365 * 60 * 60 * 24));

$months = floor(($z - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));

$days = floor(($z - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));

$hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));

$minuts = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);

$seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minuts * 60));

Output is:

4 month 4 days 1 hour 6 minute 6 seconds

Expected output is :

4 month 4 days 2 hour 6 minute 6 seconds

DateTime is a good way to work with dates in PHP:

$start = "2015-01-01 10:00:00";
$end = "2015-05-05 12:06:06";

$d1 = new DateTime($start);
$d2 = new DateTime($end);

$iv = $d2->diff($d1);

echo $iv->format('%m month, %d days, %h hours, %i minutes, %s seconds');

Nothing is wrong on your code, you probably need to include your default timezone, like for me Im in Africa, so i always use the below line to set up my timezone.

date_default_timezone_set('Africa/Harare');

you just need to fine out what is your region and then assign it to the method date_default_timezone_set();

$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';

Use following code

$start = date_create('2015-01-01 10:00:00');
$end = date_create('2015-05-05 12:06:06');
$diffObj = date_diff($start, $end);
//accesing days
$days = $diffObj->d;
//accesing months
$months = $diffObj->m;
//accesing years
$years = $diffObj->y;
//accesing hours
$hours=$diffObj->h;
//accesing minutes
$minutes=$diffObj->i;
//accesing seconds
$seconds=$diffObj->s;
echo '<center>';
echo '' . $days . ' day(s), ' . $months . ' month(s), ' . $years . 'year(s), '.$hours.' hour(s),'.$minutes.' minute(s), '.$seconds.' second(s) </b>';
echo '</center>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM