Reputation: 213
I need to be sure that two dates are in different months, I tryed this wat but I get a bad result
$to_date = "2015-01-31";
$from_date = "2015-02-01";
$date1 = date_create($to_date);
$date2 = date_create($from_date);
$interval = date_diff($date1,$date2);
$elapsed['days'] = $interval->format('%a');
$elapsed['months'] = $interval->format('%m');
------------------- alternative method
$month0 = date('n',$to_date);
$month1 = date('n',$from_date);
$elapsed['month_diff']=$month1-$month0;
-----------------------------
print_r($elapsed);
Array ( [month_diff] => 0 [days] => 1 [months] => 0 )
Any tip?
Upvotes: 2
Views: 204
Reputation: 213
Also this one works fine
$dateA1 = date_parse($to_date);
$dateA2 = date_parse($from_date);
$elapsed['month_diff']=$dateA1['month']-$dateA2['month'];
Upvotes: 0
Reputation: 54841
Second argument of date
is a timestamp, not a string. So, you should use strtotime
to get timestamp of your dates:
$month0 = date('n',strtotime($to_date));
$month1 = date('n',strtotime($from_date));
$elapsed['month_diff'] = $month1 - $month0;
Upvotes: 2
Reputation: 4010
You need to use getdate
function. This function returns array with information about date. Example:
$to_date = "2015-01-31";
$from_date = "2015-02-01";
$date1 = getdate(strtotime($to_date));
$date2 = getdate(strtotime($from_date));
if($date1["mon"] !== $date2["mon"] {
...your code....
}
Upvotes: 2