简体   繁体   English

PHP计算没有日期的两个日期之间的差

[英]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. 例如,这意味着2014年1月2日和2015年1月6日这两个日期之间的差额应为4天。

For that I changed the date format to md , and used the below method: 为此,我将日期格式更改为md ,并使用以下方法:

$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? 但是我得到的结果为0。有人可以帮助我吗? What is the mistake I am doing? 我在做什么错?

You can replace the year with 1970 and do the calculations against that. 您可以将年份替换为1970,然后根据该年份进行计算。

$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 这是PHP DateTime解决方案

$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". 只需输入日期的“ md”部分,然后在其末尾附加任何年份,例如“ -2014”。 The datediff() will then give you the required answer. 然后datediff()将为您提供所需的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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