lcjury lcjury - 1 year ago 68
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) {
$what_day = date("N", $begin);
if ($what_day > 5) {
$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
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
to avoid misunderstandings.

Answer Source

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) {
    return $weekend_count;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download