Calculate the difference in days from an array

Published 1 month ago by mstarkey

I am trying to calculate the amount of days from an array of start and end dates.

I can calculate the difference from one line using $item->start->diffInDays($item->end) but I need to produce an array of dates then add them together.

any thoughts are welcome on this.

many thanks

Mark

Best Answer (As Selected By mstarkey)
ftrillo

You're not being very clear. If you want the total number of days you could do this:

// Assuming each item represents a range of dates with a start and an end
$days = $collection->reduce(function ($carry, $item) {
    return $carry + $item->start->diffInDays($item->end);
}, 0);
ftrillo

You're not being very clear. If you want the total number of days you could do this:

// Assuming each item represents a range of dates with a start and an end
$days = $collection->reduce(function ($carry, $item) {
    return $carry + $item->start->diffInDays($item->end);
}, 0);
mstarkey

Hi @ftrillo,

Thanks for you reply/solution. I applied it to my code and the results looked promising, a very elegant solution.

however the results are not what I was expecting and i think thats due to the reduce being used on the date->diffInDays calculations rather than a flat integer.

would a foreach return the same result or does the 'reduce function' wrap that into something more user friendly?

ftrillo

diffInDays() returns an integer that's the number of days between two dates truncated down (so 23 hours is 0 days).

And reduce() is the same than doing a foreach and adding the results yourself.

How do the results differ from the expected results? Without knowing that I can't help much.

mstarkey

for some reason each entry is minus 1

e.g. (4,5,2) returns a total of 8 not 11

I have tested with several difference datasets and the result is the same, its a weird one for sure, I am aware that the diffInDays returns an integer but wondering if the hours need to be full 24 to work correctly. I can't find anything in the nesbot/Carbon docs.

thanks

Mark

mstarkey

@ftrillo,

after some more testing I have discovered that the diffInDays returns 1 less that the the 2 dates indicated i.e.

Mon, Oct 23, 2017 12:00 AM to Fri, Oct 27, 2017 11:00 PM returns 4 not 5 as expected.

so the issue is not the 'reduce' function and is as suspected the diffInDays function.

I will keep digging, but thank you for your solution, it is the correct one to use in this case.

mstarkey

The final answer is to add an extra day to the code like so:

$days = $items->reduce(function ($carry, $item) {
       return $carry + $item->start->diffInDays($item->end->addDay());
}, 0);

thanks to @ftrillo for an elegant solution to an irritating problem :)

Please sign in or create an account to participate in this conversation.