简体   繁体   中英

php compare difference between two dates

Im trying to return the difference between 2 dates, i'm working according to the example found on stackoverflow

My Problem? Im getting completely the wrong results returned, the following code returns 30 years, 0 months, 9 days, when it should obviously be only 7 days or 1 week.

Code follows below:

    date_default_timezone_set('America/Los_Angeles');

    $pickupDate = '2016-10-13';
    $returnDate  = 2016-10-20;

    $diff = abs(strtotime($pickupDate) - strtotime($returnDate));
    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

    printf("%d years, %d months, %d days\n", $years, $months, $days); 

Any input appreciated

First, the code doesn't take into account leap years, varying length of months and things like that.

There is actually a function in php for this, please check the link for details: http://php.net/manual/en/datetime.diff.php , and an example taken:

$datetime1 = new DateTime('2016-10-13');
$datetime2 = new DateTime('2016-10-20');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years, %m months, %d days');

Try this, it will give you differ in date, and , time, minutes, hour ,second ,and etc.

date_default_timezone_set('America/Los_Angeles');
$now = '2016-10-13';
$returnDate  = '2016-10-20';
$start = date_create($returnDate);
$end = date_create($now);
$diff=date_diff($end,$start);
print_r($diff);

DEMO

From the manual

 $pickupDate = new DateTime('2016-10-13');
 $returnDate = new DateTime('2016-10-20');
 $interval = $pickupDate->diff($returnDate);
 echo $interval->format('%R%a days');

http://php.net/manual/en/datetime.diff.php

date_default_timezone_set('America/Los_Angeles');

$pickupDate = '2016-10-13';
$returnDate  = '2016-10-20'; //use signle quote same as pickupDate 

$diff = abs(strtotime($returnDate) - strtotime($pickupDate)); // change the order 
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days); 

Thanks

just put single quote in return date like $returnDate = '2016-10-20'; and you can use date_diff() function of php like,

$daysdiffernce = date_diff(date_create('2016-10-13'),date_create('2016-10-20'));
echo $daysdiffernce->format("%R%a days");

and this will give exactly +7days answer

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