简体   繁体   中英

Receiving incorrect results from the PHP function strtotime()

I start with two dates:

$endDate   = '2013-11-30 18:30:00';
$beginDate = '2013-10-31 18:30:00';

Then, I took date difference using following code:

$diff = abs(strtotime($endDate) - strtotime($beginDate));

Next, I check the date difference by

$days = $diff / (60*60*24);

However, it returns a fractional day, such as 30.041666666667 . I don't want to get this fractional. Why this happening? This problem occurs in some cases only.

Try this :

$date1 = new DateTime("2013-11-21 12:59:00");
    $date2 = new DateTime("2013-11-21 13:01:00");
    $interval = $date1->diff($date2); 

    echo "DIFF: ".$interval->format("%Y-%m-%d %H:%i:%s");

Visit the link for details

you can also use mktime() function for calculate diff.

<?php
$endDate   = '2013-11-30 18:30:00';
$endDateTemp = explode(' ', $endDate);
$endDateArr1 = explode('-', $endDateTemp[0]);
$endDateArr2 = explode(':', $endDateTemp[1]);
$endTimestamp = mktime($endDateArr2[0], $endDateArr2[1], $endDateArr2[2], $endDateArr1[1], $endDateArr1[2], $endDateArr1[0]);
$beginDate = '2013-10-31 18:30:00';
$beginDateTemp = explode(' ', $beginDate);
$beginDateArr1 = explode('-', $beginDateTemp[0]);
$beginDateArr2 = explode(':', $beginDateTemp[1]);
$beginTimestamp = mktime($beginDateArr2[0], $beginDateArr2[1], $beginDateArr2[2], $beginDateArr1[1], $beginDateArr1[2], $beginDateArr1[0]);
$diff = $endTimestamp - $beginTimestamp;
$day = $diff/(24*60*60);
?>

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