Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calculating number of days between 2 dates

Tags:

date

php

I am developing a web application which revolves around dates.

I need to calculate numbers based around days elasped, for example - pseudo code

$count_only = array('monday', 'wednesday', 'friday'); //count only these days
$start_date = 1298572294;  // a day in the past
$finish_date = 1314210695; //another day

$var = number_of_days_between($start_date, $finish_date, $count_only);

Is there a way determine how many full days have elapsed, while only counting certain days?

like image 621
Mazatec Avatar asked Aug 24 '11 18:08

Mazatec


2 Answers

You can simplify this considerably by calculating how many complete weeks fall between the two specified dates, then do some math for the beginning/end partial weeks to account for dangling dates.

e.g.

$start_date = 1298572294;  // Tuesday
$finish_date = 1314210695; // Wednesday

$diff = 1314210695-1298572294 = 15638401 -> ~181 days -> 25.8 weeks -> 25 full weeks.

Then it's just a simple matter of checking for the dangling dates:

Tuesday -> add 2 days for Wednesday+Friday to get to the end of the week
Wednesday -> add 1 day for Monday to get to the beginning on the week

Total countable days = (25 * 3) + 2 + 1 = 75 + 3 = 78 countable days
like image 193
Marc B Avatar answered Sep 29 '22 16:09

Marc B


You could create a loop which goes to the next day in the $count_only array, from the $start_date and stopping (returning from the function) upon reaching the $end_date.

function number_of_days_between($start_date, $finish_date, $count_only) {
    $count  = 0;
    $start  = new DateTime("@$start_date");
    $end    = new DateTime("@$finish_date");
    $days   = new InfiniteIterator(new ArrayIterator($count_only));
    foreach ($days as $day) {
        $count++;
        $start->modify("next $day");
        if ($start > $end) {
            return $count;
        }
    }
}
like image 37
salathe Avatar answered Sep 29 '22 15:09

salathe