PHP的天数为几个月

时间:2013-04-10 10:16:27

标签: php operators date-range date-arithmetic

我正在尝试使用天数输出数月($ daydiff的价值)。

整个代码如下:

$ArrivalDate = $variants_data['ArrivalDate'];

$daydiff=floor((abs(strtotime(date("Y-m-d")) - strtotime($ArrivalDate))/(60*60*24)));


if (!empty($daydiff) &&  $ArrivalDate == '2013-12-25') {
    $ETA ='Date Not Confirmed';
} 

elseif (!empty($daydiff) &&  is_null($ArrivalDate)) {
    $ETA ='Not available';
}

elseif ( $daydiff > 30 && $daydiff < 60 ) { // anything between 31 and 59 days is 1 month
    $ETA ='1 Month';
}

elseif ( $daydiff > 60 &&  $daydiff < 90  )  { // anything between 61 and 89 days is 2 months
    $ETA ='2 Months';
}

else
{
    $ETA ='';
}

此部分代码未向我提供所需结果

elseif ( $daydiff > 30 && $daydiff < 60 ) { // anything between 31 and 59 days is 1 month
    $ETA ='1 Month';
}

elseif ( $daydiff > 60 &&  $daydiff < 90  )  { // anything between 61 and 89 days is 2 months
    $ETA ='2 Months';
}

else
{
$ETA ='';
}

我得到'未确认日期'作为结果。如果$ daydiff值落在范围内,则所需结果为“1个月”或“2个月”。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

    $ArrivalDate = $variants_data['ArrivalDate'];

if (!empty($ArrivalDate)){
    $ArrivalDate = date('Y-m-d', strtotime($ArrivalDate));

    $daydiff=floor(abs(strtotime(date("Y-m-d")) - strtotime($ArrivalDate)) / (60*60*24));

    echo $daydiff;

    if ($ArrivalDate == '2013-12-25') {
        $ETA ='Date Not Confirmed';
    }
    elseif ( $daydiff > 30 && $daydiff < 60 ) { // anything between 31 and 59 days is 1 month
        $ETA ='1 Month';
    }

    elseif ( $daydiff > 60 &&  $daydiff < 90  )  { // anything between 61 and 89 days is 2 months
        $ETA ='2 Months';
    }
    else
    {
        $ETA ='';
    }
} else {
    $ETA ='Not available';
}

答案 1 :(得分:0)

试试这个 这里是一个简单的例子来计算月份中的日期差异而没有额外的if else条件

<?php

$date1=date('2013-1-1');
$date2=date('2013-5-2');

echo "date1 :: ".$date1."<br>";
echo "date2 :: ".$date2."<br>";

$date_diff=strtotime($date2)-strtotime($date1);

echo "date difference in months => ".floor(($date_diff)/2628000)." months <br>";
?>