How to get difference month from 2 date PHP? - php

i have date
$d1='2014-02-01';
$d2='2013-11-01';
i want if i minus $d2 - $d1 = i get difference of month = -3 and if $d1 - $d2 = 3 ,
Any one can help, sorry for my bad english

$d1= new DateTime('2014-02-01');
$d2= new DateTime('2013-11-01');
$diff = $d1->diff($d2);
echo $diff->format("%r%m");
Demo

Related

Count number of months by day in php

I want to get month between two dates. I've googled a lot but still don't have the answer.
$date1 = new \DateTime("2021-07-20");
$date2 = new \DateTime("2021-08-15");
$interval = $date2->diff($date1);
dd($interval->m); // 0 months.
Above, counting $date1 and $date2 is less than 30 days so it returns 0 months which is correct. But now I want to get the result 2. It's July and August. Is there any way to get that?
Thanks
I tried a few approaches to tackle this.
The easiest method I've found that works for all use cases involves using regular math rather than date functions. The date diff methods I've tried all gave incorrect answers at some point because of the differing number of days in a month.
function getCoveredMonths(DateTime $date1, DateTime $date2): int {
$earlierDate = min($date1, $date2);
$laterDate = max($date1, $date2);
$earlierMonthValue = $earlierDate->format("Y") * 12 + $earlierDate->format("n");
$laterMonthValue = $laterDate->format("Y") * 12 + $laterDate->format("n");
return $laterMonthValue - $earlierMonthValue + 1;
}
// Your example
$date1 = new DateTime("2021-07-20");
$date2 = new DateTime("2021-08-15");
var_dump(getCoveredMonths($date1, $date2));
// 2: July + August
// Same month
$date3 = new DateTime("2021-07-15");
$date4 = new DateTime("2021-07-20");
var_dump(getCoveredMonths($date3, $date4));
// 1: July
// Day overflow test (01-30 + 1 month = 02-30 which overflows to 03-02)
$date5 = new DateTime("2021-01-30");
$date6 = new DateTime("2021-03-01");
var_dump(getCoveredMonths($date5, $date6));
// 3: January + February + March
// Year pass test
$date7 = new DateTime("2021-12-20");
$date8 = new DateTime("2022-02-15");
var_dump(getCoveredMonths($date7, $date8));
// 3: December + January + February
// Wrong order ($date2 is before $date1)
$date9 = new DateTime("2021-10-20");
$date10 = new DateTime("2021-08-15");
var_dump(getCoveredMonths($date9, $date10));
// 3: August + September + October
<?php
$origin = new \DateTime('2020-08-01');
$target = new \DateTime('2021-12-01');
$interval = $origin->diff($target);
echo (($interval->format('%y') * 12) + $interval->format('%m'));
// output is 16 months
?>
If you want to calculate with the full months, you have to calculate from the 1st of the start month to the 1st after the end of the month.
$date1 = new \DateTime("2021-07-20");
$date2 = new \DateTime("2021-08-15");
//
$date1->modify('first day of this Month'); //2021-07-01
$date2->modify('first day of next Month'); //2021-09-01
$interval = $date1->diff($date2);
$countMonth = $interval->m; //2

calculate day difference between two unix timestamps at boundary values

I have two timestamps created against dates 02/09/2014 11:30pm and 03/09/2014 12:00am.
There is only 30 minutes difference between these timestamps but as date has changed from O2 October to 03 October, it should be calculated as a day.
My code is
$current_time_zone = isset($_COOKIE['IANA_timezone_key']) ? $_COOKIE['IANA_timezone_key'] : "";
$d1 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d2 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d1->setTimestamp($row["transitions_date"]); // $row["transitions_date"] has timestamp value
$d2->setTimestamp($curr_transition_in_date); // $curr_transition_in_date has timestamp value
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
Any help will be highly appreciated.
You could not expect your desired day difference from the returning object of date_diff() as it is based on the actual time difference. The easiest way would be to adjust it yourself.
$d1 = new DateTime(date('Y-m-d'));
$d2 = new DateTime(date('Y-m-d'));
$d1->setTimestamp($row["transitions_date"]);
$d2->setTimestamp($curr_transition_in_date);
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
echo 'Actual output from date_diff: '.$day_difference;
echo '<br>';
if($d2->format('H:i:s') < $d1->format('H:i:s')){
$day_difference++;
}
echo 'Corrected output: '.$day_difference;
Demo 1 for the different day, but same month and year.
Demo 2 for the same day, but different month and year.
Demo 3 for the same output.

date_diff returns 0 if the difference is over a year

I am using this function to get month difference between two dates.
$interval = date_diff(date_create('2015-10-08'), date_create('2014-10-10'));
$total_months = $interval->format('%m');
RESULT: 11 (That's Correct!)
But, When the difference is over a year, then,
$interval = date_diff(date_create('2015-11-08'), date_create('2014-10-10'));
$total_months = $interval->format('%m');
RESULT: 0 (That's Wrong!)
why is it returns 0? Is there any way by which I can get difference between any 2 dates? Thanks!
2015-11-08 to 2014-10-10 is 12 months become a year. So it returns 0 month. Calculate the number of years from the $interval then add (year * 12) to the number of months. Example here...
$interval = date_diff(date_create('2015-11-08'), date_create('2014-10-10'));
$year = $interval->format('%Y');
echo $total_months = $interval->format('%m') + $year * 12;
Or better:
$total_months = $interval->y * 12 + $interval->m;
You have years and months as fields, no need to use format to obtain parts as texts for later adding the parts!
It is a bit tricky and needs a work round , try the following, that could
be it.
$first = new DateTime('2015-11-08',new DateTimeZone('America/New_York'));
$second = new DateTime('2014-10-10',new DateTimeZone('America/New_York'));
$diff = $second->diff($first);
$months = (Int)($diff->days/30);
echo "The two dates have $months months between them.";
Output:The two dates have 13 months between them.

Subtract two dates to display number of Days

<?php
$datetime1 = new DateTime("$da[tofollowon]");
$datetime2 = new DateTime();
$difference = $datetime1->diff($datetime2);
$days = $difference->days;
?>
Above php code displays difference in two dates, but i want to subtract these two dates datetime2 from datetime1 which should even display negative values.
Try this
$d1 = strtotime("2014-01-10"); // or your date as well
$d2 = strtotime("2014-01-01");
$datediff = $d1 - $d2;
echo floor($datediff/(60*60*24)).' days';
try
$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');
$days_between = ceil(abs($end - $start) / 86400);
For more :- Finding the number of days between two dates

how to calculate days between two days including start date and end date

Consider two dates '2011-01-01' and '2011-01-02'.I want to calculate the number of days between these two dates.The result what I want is 2 days(i.e including both start and end date).I used several date functions in php and mysql,but all returns 1 as the answer.
$date11 = '2011-01-01';
$date22 = '2011-01-02';
$dt1 = new DateTime($date11);
$dt2 = new DateTime($date22);
$diff = $dt2->diff($dt1);
echo $diff->format("%a");
Any solution in php or mysql would be grateful.Thanks in advance.
If you want to get 2 days for this interval you can just +1 to the result, because none of the combinations of functions will give 2 days.
$date11 = strtotime($date11);
$date22 = strtotime($date22);
$diff = $date22 - $date11;
$diff_in_days = floor($diff/(60*60*24)) + 1;
Example
You can use DateTime and DateInterval and do you add 1 day?
DateTime
DateInterval
<?php
$d1 = new DateTime('2011-01-01');
$d2 = new DateTime('2011-01-02');
$d2->add(new DateInterval('24h'));
$interval = $d2->diff($d1);
$interval->format('%d Days');
$interval->format('%h Hours');
?>
in mysql:
select abs(datediff('2011-01-01','2011-01-02'))+1 as difference;
+------------+
| difference |
+------------+
| 2 |
+------------+
1 row in set (0.00 sec)
datediff() returns the number of days between the two dates, abs() makes sure we don't get negative values when switching first and second date and the final +1 because you wanted start and enddate to be included in the number.
Use DateDiff. The online docs have this answer as the first example:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$datetime2->modify("+1 days");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // output
Another way to do this:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
$diff = $interval->days + 1;
echo $diff . " days.";

Categories