Robin
Robin

Reputation: 1587

Laravel division by zero if date is today

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?

Upvotes: 0

Views: 1807

Answers (1)

Pᴇʜ
Pᴇʜ

Reputation: 57743

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)

Upvotes: 1

Related Questions