简体   繁体   中英

PHP calculate difference between two dates WITHOUT year

I generally use this method to calculate difference between two dates:

$datediff = strtotime($enddate) - strtotime($startdate);        
$totalDays = floor($datediff/(60*60*24));

But now I got a problem. Now I should not consider the year in the calculation. Which means for example the difference between two dates January 2 2014 and January 6 2015 should give me result as 4 days.

For that I changed the date format to md , and used the below method:

$startdate = date('m-d',strtotime($startdate));
$enddate = date('m-d',strtotime($enddate));
$datediff = $enddate - $startdate;
$totalDays = floor($datediff/(60*60*24));

But I get the result as 0. Can anyone help me? What is the mistake I am doing?

You can replace the year with 1970 and do the calculations against that.

$date1 = '2014-01-17 04:05:54';
$date2 = '2013-01-12 02:07:54';

$date1 = preg_replace('/([\d]{4})/', '1970', $date1);
$date2 = preg_replace('/([\d]{4})/', '1970', $date2);

$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);

$date_diff = gmdate('d H:i:s', abs($timestamp2-$timestamp1));

var_dump($date_diff);

Please try this :

$startdate = 'January 1 2014';
$enddate =  'February 6 2015';
$startdate = date('d-m-1970',strtotime($startdate));
$enddate = date('d-m-1970',strtotime($enddate));
$datediff = strtotime($enddate) - strtotime($startdate);
$totalDays = floor($datediff/(60*60*24));
echo $totalDays;

Hope this will help

here is the php DateTime solution

$date1 = new DateTime('2015-01-02');
$date2 = new DateTime('2014-01-06');

switch (true) {
    case ($date1 < $date2) :
        $date2->setDate($date1->format('Y'), $date2->format('m'), $date2->format('d'));
        break;

    case ($date2 < $date1) :
        $date1->setDate($date2->format('Y'), $date1->format('m'), $date1->format('d'));
        break;
}

$interval = $date1->diff($date2);
echo $interval->format('%R%a days'); // +4 days

have fun!

Or just cut off the year and leave away the switch part.

Just take the "md" part of your date and append any year onto the end of it, eg "-2014". The datediff() will then give you the required 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