PHP calculates the number of days between two dates

I am developing a web application that revolves around dates.

I need to calculate numbers based on days, e.g. 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 to determine how many days have passed, but only counting certain days?

+5
source share
4 answers

You can create a loop that goes the next day into an array $count_only, starting at $start_dateand stopping (returning from a function) when it is reached $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;
        }
    }
}
+2
source

, , , / , .

.

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

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

:

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
+3

, : -)

$elapsed_days = floor(($finish_date-$start_date) / 86400);

. , (pesudo):

$elapsed_days = floor(($finish_date-$start_date) / 86400);
for(int $i=0;$i<$elapsed_days;$i++){
  $act_day_name = strtolower(date('l',$start_date+$i*86400));
  if(in_array($act_day_name,$count_only){
    // found matching day
  }
}

: , , ('l'); , . , , .

+2

, " ":

$count_only = array(1, 3, 5); // days numbers from getdate() function
$start_date = 1298572294;
$finish_date = 1314210695;

function days($start_date, $finish_date, $count_only)
{
    $cnt = 0;

    // iterate over 7 days
    for ($deltaDays = 0; $deltaDays < 7; $deltaDays++)
    {
        $rangeStart = $start_date + $deltaDays * 86400;

        // check the weekday of rangeStart
        $d = getDate($rangeStart);
        if (in_array($d['wday'], $count_only))
        {
            $cnt += ceil(($finish_date - $rangeStart) / 604800);
        }
    }

    return $cnt;
}

, , , , ..

+2

All Articles