Count number of months by day in php - 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

Related

php: Calculate Date from Week of Year and Day of Week

I am currently struggling with the following: I need to get the Date like "Sun, 29.05.2016 18:00" but all i have is the number of the week from the beginning of the year, the number of the day of week and the hour of the day.
Week: 21
Day: 7
Hour: 18
Now my question is how do i get the actual date and time with php's date functions or own code?
You are looking for DateTime::setISODate
$week_no = 21;
$day =7;
$hour = 18;
$d= new DateTime();
$d->setISODate(date('Y'),$week_no, $day);
$d->setTime ($hour,0);
echo $d->format('D, d.m.Y H:i');
Pretty straightforward with DateTime objects:
$week = 21;
$day = 7;
$hour = 18;
$dateFormat = sprintf('%d-W%02d-%d', (new DateTime())->format('Y'), $week, $day);
$x = new DateTime($dateFormat);
$x->setTime($hour, 0);
echo $x->format('Y-m-d H:i:s');
(assuming the current year)
Try with setISODate and DateTime. Online Check
Setting the 2016 from your desire output and use the hour directly to the format.
$gendate = new DateTime();
$gendate->setISODate(2016, 21, 7); //year , week num , day
echo $gendate->format('D, d.m.Y 18:00'); //Sun, 29.05.2016 18:00

Adding dates incorrectly

Hi I'm not sure how get this equation correct because I not sure about the dates. I know it returns the same date but I'm trying to learn different formats and how to add dates different days. I know may not be the best way of writing the code I still would like to know how to write this code. The equation is :
$mhYr + ($vSDday -1day)
My code:
$date = "2015-11-02";
$vStartDate = strtotime($date);
$currentdate = $vStartDate;
$vSDday = date('d', $currentdate); //day
$monthY = date('m', $currentdate); //Month
$mhYr = date("01-$monthY"); //first day of any month
But I keep getting errors because of the dates.
An example would be 1stOfMonth + (daysOfStartDate -1 day). So if I started on the 2 November i want to perform : 1st Nov + (2 - 1day). But I don't know how to put all together.
When you do :
$date = "2015-11-02";
$vStartDate = strtotime($date);
and try to print it ( echo $vStartDate), it will print number of seconds difference between 1 january 1970 at midnight and 2015-11-02 , to convert the time to human readable format you need getdate($vStartDate ), it will return collection format.
$date = "2015-11-02";
$vStartDate = strtotime($date);
$timeCollection= getDate($vStartDate);
Then you can start doing :
$day = $timeCollection["mday"]; //day
$month = $timeCollection["mon"]; // month
$year = $timeCollection["year"]; // year
$hour = $timeCollection["hours"]; // hours
$minute = $timeCollection["minutes"]; // minutes
$seconds = $timeCollection["seconds"]; // seconds

Calculating time difference for fixed hour

I want to calculate the time difference from now (lets say 18:30:00) till this evening at 20pm.
$today = date('Y-m-d', time());
$remain = strtotime($today. " 00:00:00 + 20 hours") - time();
$remain = date('H:i:s', $remain);
I get a result which is one hour larger (02:30:00) than the actual result (01:30:00). I tried setting time zones but it's always the same result.
Using the DateTime object, you can do this easily:
$d1 = new DateTime('2015-04-23 18:30');
$d2 = new DateTime('2015-04-23 20:00');
$interval = $d2->diff($d1);
echo $interval->format('%H:%i hours');

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.

Check how many days were passed since the last update in PHP

I am trying to check how many days were passed since the user last entered the system. I get the last time he\she entered from mysql table column (datetime). so I wrote :
$user_last_visit = $user_info['last_updated']; // 2013-08-08 00:00:00
$user_last_visit_str = strtotime($user_last_visit); // 1375912800
$today = strtotime(date('j-m-y')); // 1250114400
$diff = $today - $user_last_visit_str;
Where $user_info['last_updated'] has the last time he\she visited with the value of 2013-08-08 00:00:00.
After strtotime I get $user_last_visit_str equals to 1375912800
$today has the value of 9-08-13 and after strtotime I get 1250114400.
Some reason $diff = $today - $user_last_visit_str; is negative instead of getting a positive value with 24*60*60*1000 (one day = 24*60*60*1000 ms).
Any ideas?
A simple solution using diff:
echo date_create()->diff(date_create($user_last_visit))->days;
If all else fails, just do:
$diff = floor((time() - $user_last_visit_str) / (60 * 60 * 24));
you can use below code to get date diff, here i given static last date which is 15th july 2013, and taking different from current date.
$last_date = date('y-m-d', strtotime('15th july 2013'));//here give your date as i mentioned below
//$last_date = date('y-m-d', strtotime($your_old_date_val));
$current_date = date('y-m-d');//
echo $date_diff = strtotime($current_date) - strtotime($last_date) ;
echo $val = 60*60*24;
$days_diff = $date_diff / $val;
echo $days_diff;
Try this:
$user_last_visit = $user_info['last_updated']; // considering the value of user last visit is 2013-08-08 00:00:00 which indicates year, month, day, hour, minute, second respectiveliy
$user_last_visit_str = strtotime($user_last_visit);
$today = time();
$diff = $today - $user_last_visit_str;
$no_of_days = ($diff / (60*60*24));
Try using a DateTime object if your version of PHP supports it:
$user_last_visit = DateTime::createFromFormat('Y-m-d H:i:s', $user_info['last_updated']);
$today = new DateTime();
$diff = $today->diff( $user_last_visit, true );
echo $diff->days;
$diff will be a DateInterval object.
try reversing the $today assignment, like so:
$today = strtotime(date('y-m-j'));
that worked for me.

Categories