Laravel division by zero if date is today - php

I'm trying to make some stats for my website.
But I have the problem that if I use the code I got now, when it is a dy like today, so the first day of the month, I got the error division by zero.
My code:
$begin = date('Y-m-01');
$end = date('Y-m-t');
$begin = new \DateTime($begin);
$end = new \DateTime('now');
$diff = $end->diff($begin); // creates a DateInterval object
$days = (int)$diff->format('%a'); // %a --> days
$average_visits = $get_visits / $days;
It does work, when the day isn't 01 or 1.
How can I fix his issue?

It is because $days actually is zero!
Explanation
Today is 2015-07-01 (at least here at my timezone)
you define $begin = date('Y-m-01'); which is 2015-07-01
you define $end = new \DateTime('now'); which is 2015-07-01
you want to know the difference in days which is 0
$diff = $end->diff($begin);
$days = (int)$diff->format('%a');
you divide a unknown number $get_visits by $days (which is zero).
So you get the correct error division by zero.
Possible Solution
If you mean that $days fully includes the beginning day and the end day then use
$days = (int)$diff->format('%a') + 1;
Then
a) begin = 2015-07-01, end = 2015-07-01
b) begin = 2015-07-01, end = 2015-07-05
a) means this is 1 day
b) means these are 5 days (day 2015-07-01, day 2015-07-02, day 2015-07-03, day 2015-07-04 and day 2015-07-05 makes 5 days)

Related

Days spent between now and n date [PHP]

Okay! so we all have seen how to get days remaining between NOW and a DATE in the future Like I have in my simple code below:
SAY: $endate = a date in future (5 days from today);
$start = new DateTime();
$end = new DateTime($enddate);
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
echo $days.'Days Remaining'; // 5 days Remaining
The above PHP Code is expected to show you how many days are left between NOW and the FUTURE DATE.
But what I want is the reverse of this situation. That is.
instead of having
5 Days Remaining
I need some thing like
0 Day(s) Spent //where today is day 0 of 5
$start = new DateTime("2021-12-14");
$now = new DateTime();
$now_diff = $now->diff($start)->format("%a");
print_r($now_diff .' Day(s) Spent');
Finding the number of days between two dates
CLUE TO ANSWER PROVIDED BY #KHIMAJI VALUKIYA in comment
The trick here is to set the start date not as current date but the actual date to start counting/calculating from.
Then the end date should be set to the current date.
$start = new DateTime($enddate); //date to start counting from
$end = new DateTime(); //current date
$diff = $end->diff($start)->format('%a');
$days = intval($diff);
echo $days.'Days Spent'; // 5 Days Spent

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

PHP Calculate Exact number of hours minutes and seconds between two timestamps

I have two Timestamps
2016-01-01 00:00:00
2016-01-02 23:59:59
Using PHP how can I calculate the number of hours and minutes between the two times and get the result as a decimal with 2 places after the .
currently I have this:
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = date_diff($Start,$Finish);
$Hours = $Interval->format('%h.%i');
But the result is incorrect if the user starts the timer on Day 1 and finishes on day 2.
You could multiply the number of days by 24 to convert them to hours, then sum the hours and concatenate the minutes:
$start = new DateTime('2016-01-01 00:00:00');
$end = new DateTime('2016-01-02 23:59:59');
$interval = $end->diff($start);
$days = $interval->format('%d');
$hours = 24 * $days + $interval->format('%h');
echo $hours.':'.$interval->format('%i');
You could format the DateTime as a UNIX timestamp, and then simply subtract to get the total seconds, and format the output with gmdate().
$Start = new DateTime($StartTime);
$Finish = new DateTime ($FinishTime);
$Interval = $Start->format('U') - $Finish->format('U');
$Hours = gmdate("H:i:s", $Interval);
Try this.
$Hours = $Interval->format('%a.%h.%i');

Correct no of days/weeks between 2 days?

I have created a function to work out the amount of days and then weeks between 2 dates, in the example below there is 35 days resulting exactly 5 weeks, however the function is returning just short of this at 4.8571428571429 - the division is killing the remainder and coming out at 4.
I could use the ceil function to round it up to 5 but is this this a safe method for all dates? or is there a better way to do it?
$date1 = new DateTime('2015-02-23');
$date2 = new DateTime('2015-03-29');
$diff = $date2->diff($date1)->format("%a");
$weeks = $diff / 7;
return $weeks;
$date2->add(new DateInterval('P1D'));
Use this line after your $date2 initialisation.
Why will this work?
If you count, you have 34 days now: FROM 23-02 0:00 TILL 29-03 0:00.
If you want to count this last day also (to have 35 days), you'll need to add an extra day.
Add a single day to $date2
$date1 = new DateTime('2015-02-23');
$date2 = new DateTime('2015-03-29');
$date2->add(new DateInterval('P1D'));
$diff = $date2->diff($date1)->format("%a");
$weeks = $diff / 7;
return $weeks;
However, you still don't have a whole number of weeks difference with your original dates

PHP get date after one week and calculate the number of days left

I have a dynamic date, now what i want is that finding the date after exact one week, i have achieved that with the code below, but now i want that now many days are left for that week after date to come. i have got some sort of time stamp, but i don't know how to convert it to DAYS LEFT.
$weekDate = date( "d/m/Y", strtotime("19-05-2014") + 86400 * 7 );
echo $weekDate;// THATS PERFECT
////////////////////////////////////////////////////////////////
$future = strtotime( $weekDate ); //Future date.
$datediff = time() - $future;
$days = floor( ( ( $datediff / 24 ) / 60 ) / 60 ); //this is not perfect, returns some
sort of timestamp
I have tried other methods which are fine, but if week completes on 26, and today is 25th it gives me 0 days left, but it should say 1 day left. please help me.
In your $date_diff now is less than the future date thats why its zero. Inside strtotime() function, you can directly put a relative date inside. In this case, for one week you can use +1 week or +7 days. Consider this example:
$next_week = date('d/m/Y', strtotime('19-05-2014 +1 week')); // 26/05/2014
$next_week = strtotime('19-05-2014 +7 days');
$difference = $next_week - time(); // next weeks date minus todays date
$difference = date('j', $difference);
echo $difference . (($difference > 1) ? ' days ' : ' day ') . ' left';
// should output: 1 day left
Alright. I did something. Here's the code
$startDate = strtotime("19-05-2014");
$endDate = $startDate + 604800;
$diff = ($endDate - time()) / 60 / 60 / 24;
if ($diff < 1 && $diff > 0) {
$days = 1;
} else {
$days = floor($diff);
}
echo $days;
The problem you have with getting "1 day" if the date is tomorrow is the floor method. strtotime() gives you the time at 0 a.m. if you don't set it by your own. Because of that the difference between now and tomorrow is less than 1 which is 0 if you floor that. I created an if-clause for that.
But that will give you "1 day" for today and "1 day" for yesterday (last 2 days before the final date). If you want that better, you have to specify time in your initial date (19-05-2014).
Use DateTime for date and time calculations.
$weekDate = new \DateTime('+ 1 week');
$future = new \DateTime('+ 3 days');
$daysLeft = $weekDate->diff($future)->days;
echo $daysLeft; //4
See it working.
Reference http://php.net/datetime

Categories