Reputation: 19
I know is silly question, but i need u help guys.
Theres something weird if i use datediff,
example
$begin = "2016-01-01"; $end = "2016-01-31";
$date1=date_create(date_format($begin,"Y-m-d"));
$date2=date_create(date_format($end,"Y-m-d"));
$diff=date_diff($date1,$date2); $month = $diff->format("%m");
when i echo $month is show 0
. It should be 1
, because Last Day of January is 31
Days. But why does it is show 0
?
If i change $end = "2016-02-01";
is becomes 1
. Can u help me this??
Upvotes: 1
Views: 59
Reputation: 772
you can try this,
<?php
$begin = "2016-01-01"; $end = "2016-01-31";
$date1=new DateTime($begin);
$date2=new DateTime($end);
$date2->add(new DateInterval('P1D'));
$diff=$date2->diff($date1);
$month = $diff->m;
print_r($month);
?>
Upvotes: 0
Reputation: 1377
<?php
$timeStart = strtotime("2016-01-01");
$timeEnd = strtotime("2016-01-31");
// Adding current month + all months in each passed year
$months = 1 + (date("Y",$timeEnd)-date("Y",$timeStart))*12;
// Add/subtract month difference
$months += date("m",$timeEnd)-date("m",$timeStart);
echo $months;
?>
Upvotes: 0
Reputation: 480
It's returning the correct answer as there is a difference of 30 days only so a month has not passed yet.
Upvotes: 1