سؤال

Consider there are 44 days between two dates.The result what I want is 2 months and not 1 month or 1 month 14 days.I have tried several date functions in both php and mysql,but failed in obtaining the exact result. I've also tried my own(below)code.

 $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;
   }

But I failed.The code is about adding vacation days to the client.Any solution in php or mysql would be grateful.Thanks in advance for all the volunteers.

هل كانت مفيدة؟

المحلول

Using PHP 5.3, maybe you could try the following:

<?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!";
?>

نصائح أخرى

Try to check number of days, if not equal to zero, then add 1 to months count and return that value of months.

<?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)";
?>

John Riedel answer is the correct one!

You need to use $start_date->diff($end_date)->m & $start_date->diff($end_date)->d to find out the month & date differences.. and if the days count is more than 0, then you need to increase the months count as stated here...

http://www.phpguy.in/finding-difference-between-2-dates-in-php/

    $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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top