Domanda

I have a startdate, let's say this is $startDate = 2012-08-01; and I have a variable that stores an INT value, lets say this is $value = 10;

I would like to calculate what the date would be from startdate + 10 days and skip weekends.

Using the above values the result would be 2012-08-15

How would this be done?

È stato utile?

Soluzione

This is far from efficient, but who cares about that right when it is readable? :)

<?php
function calculateNextDate($startDate, $days)
{
        $dateTime = new DateTime($startDate);

        while($days) {
            $dateTime->add(new DateInterval('P1D'));    

            if ($dateTime->format('N') < 6) {
                $days--;
            }
        }

        return $dateTime->format('Y-m-d');
}

echo calculateNextDate('2012-08-01', 10); // return 2012-08-15

DEMO

What happens should be pretty easy to follow. First we create a new DateTime object using the date provided by the user. After that we are looping through the days we want to add to the date. When we hit a day in the weekend we don't subtract a day from the days we want to add to the date.

Altri suggerimenti

you can use php's strtotime function to + n days/hours etc..,

and for excluding weekends have a look here: 32 hours ago excluding weekends with php

Try this

<?php
function businessdays($begin, $end) {
    $rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
    $rend = is_string($end) ? strtotime(strval($end)) : $end;
    if ($rbegin < 0 || $rend < 0)
        return 0;

    $begin = workday($rbegin, TRUE);
    $end = workday($rend, FALSE);

    if ($end < $begin) {
        $end = $begin;
        $begin = $end;
    }

    $difftime = $end - $begin;
    $diffdays = floor($difftime / (24 * 60 * 60)) + 1;

    if ($diffdays < 7) {
        $abegin = getdate($rbegin);
        $aend = getdate($rend);
        if ($diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
            return 0;
        $abegin = getdate($begin);
        $aend = getdate($end);
        $weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
    } else
        $weekends = floor($diffdays / 7);
    return $diffdays - ($weekends * 2);
}

function workday($date, $begindate = TRUE) {
    $adate = getdate($date);
    $day = 24 * 60 * 60;
    if ($adate['wday'] == 0) // Sunday
        $date += $begindate ? $day : -($day * 2);
    return $date;
}

$def_date="";//define your date here
$addDay='5 days';//no of previous days  
date_add($date, date_interval_create_from_date_string($addDay));
echo businessdays($date, $def_date); //date prior to another date 
?>

Modified from PHP.net

if you just want to add up a date +10, you may wanna consider this:

date("Y-m-d", strtotime("+10 days"));

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top