lcjury lcjury - 1 month ago 8
PHP Question

Date consideras a Timestamp from the future as a date from the past

I have a loop who counts weekend days, it works like this:

$weekends = 0;
while ($begin <= $today) {
$no_days++;
$what_day = date("N", $begin);
if ($what_day > 5) {
$weekends++;
};
$begin += 86400;
};


$begin is the first day of the month, and $today is today and I get them like this:

$begin = date("Y-m-01");
$today = date("Y-m-d");


$begin and $today are correct, but for some reason my loop is saying that 3 consecutive days are weekend. I printed te value of $begin on inside the if for debuggin reasons and I get the following output:


2016-11-05 12:11:00(1478329200)

2016-11-06 12:11:00(1478415600)

2016-11-06 11:11:00(1478502000)


Instead, what I expect to get is:


2016-11-05 12:11:00(1478329200)

2016-11-06 12:11:00(1478415600)

2016-11-07 12:11:00(1478502000)


This script as been working good for several months, but today stop working. I have a
date_default_timezone_set('America/Los_Angeles');
at the beggining.

I don't completely understand how dates works, so, i'm not really sure how to start looking for the problem, so, if this is a timezone related problem and somebody whant to point me to a source of information to learn on this topic I will be really happy :)

EDIT: As @Devon points out. I changed
$end
for
$today
to avoid misunderstandings.

Answer

You should consider working with PHP's DateTime, DateInterval, and DatePeriod classes.

function countWeekendDaysBetween(DateTime $start, DateTime $end) {
    $weekend_count = 0;
    // one day interval
    $interval = new DateInterval('P1D');
    // get date period object based on start, end, interval
    $date_period = new DatePeriod($start, $interval, $end);
    foreach($date_period as $dt) {
        if ((int)$dt->format('N') > 5) {
            $weekend_count++;
        }
    }
    return $weekend_count;
}