lcjury lcjury - 25 days ago 10
PHP Question

Date considers 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.

EDIT 2: Please people, if you're going to downvote this question, provide a comment telling what is wrong, I don't care about points, but I care about being a good user in SO. If you're going to down vote my question and wont provide a comment explaining what's wrong you're not making SO a better please, but a bitter one.

Answer

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

function countWeekendDaysBetweenDateTimes(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;
}

These classes will be much more reliable to work with when dealing with ranges and recurrences of dates and will generally also simplify dealing with timezones (DateTimeZone), daylight savings, leap years, and other anomalies of our calendar and time systems.

Comments