考虑两个日期之间有44天。我想要的结果是2个月而不是1个月或1个月14天。我在php和mysql中尝试了几个日期函数,但未能获得确切的结果。我也尝试了自己的(下面)代码。
$dt1 = some date
$dt2 = some date
$date1 = date_create("".$dtl."");
$date2 = date_create("".$dt2."");
$dateDiff = date_diff($date2, $date1);
$probDays = $dateDiff->days;
$probMon = $dateDiff->m;
$probYear = $dateDiff->y;
$month = $probDays / 30;
$totLeave = $month * 1;
if($month > $probmon)
{
$totLeave = $totLeave + 1;
}
但我失败了。代码是关于为客户添加休假日。在php或mysql中的任何解决方案都会感激不尽。谢谢所有志愿者。
答案 0 :(得分:1)
尝试检查天数,如果不等于零,则添加1到月计数并返回该月值。
答案 1 :(得分:1)
使用PHP 5.3,也许您可以尝试以下方法:
<?php
$dt1 = "2014-05-12";
$dt2 = "2014-06-15";
$date1 = new DateTime($dt1);
$date2 = new DateTime($dt2);
$months = $date1->diff($date2)->m;
$days = $date1->diff($date2)->d;
if ($days >= 1) $months++;
echo $months." months!";
?>
答案 2 :(得分:0)
<?php
$dt_dif= $dt2 - $dt1 ;
$y = $tot_exp / 365;
$d = $tot_exp % 365;
$m = $d / 30;
$year = (int)$y;
$month = (int)$m;
$day= (int)$d;
$total="".$month."month(s) ".$day."day(s)";
?>
答案 3 :(得分:0)
John Riedel的答案是正确答案!
您需要使用$ start_date-&gt; diff($ end_date) - &gt; m&amp; $ start_date-&gt; diff($ end_date) - &gt; d找出月份&amp;日期差异..如果天数大于0,那么您需要增加此处所述的月数......
http://www.phpguy.in/finding-difference-between-2-dates-in-php/
答案 4 :(得分:0)
$date_from = "2011-01-22";
$date_to = "2011-03-23";
$date_from = date('Y-m-d', strtotime($date_from));
$date_to = date('Y-m-d', strtotime($date_to));
$y1 = date('Y', strtotime($date_from));
$y2 = date('Y', strtotime($date_to));
$m1 = date('m', strtotime($date_from));
$m2 = date('m', strtotime($date_to));
$day1 = date('d', strtotime($date_from));
$day2 = date('d', strtotime($date_to));
$yearDiff = $y2 - $y1;
if ($m2 > $m1) {
$month = $m2 - $m1;
} else {
$month = 0;
}
if ($yearDiff > 0 && $m1 > $m2) {
$yearMonth = (($yearDiff * 12) - ($m1 - $m2));
} else {
$yearMonth = $yearDiff * 12;
}
if ($day1 > $day2) {
$month = ($month - 1);
}
$total_month = $yearMonth + $month;
$total_month = ($total_month > 1) ? $total_month . " months" : $total_month . " month";
echo "Total " . $total_month;