Reputation: 1191
So, I have this function:
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');
}
If I run my function like this:
echo calculateNextDate('2012-10-01', '10');
It will result in:
2012-10-15
Which is correct, however I would like it to count the $startDate
as a counted day, so it will count like this:
1. 2012-10-01
2. 2012-10-02
3. 2012-10-03
4. 2012-10-04
5. 2012-10-05
6. 2012-10-08
7. 2012-10-09
8. 2012-10-10
9. 2012-10-11
10. 2012-10-12
Is it possible?
Upvotes: 0
Views: 264
Reputation: 238
<?
function calculateNextDate($startDate, $days)
{
$dateTime = new DateTime($startDate);
while($days > 0) {
$weekend = date('w', strtotime($dateTime->format('Y-m-d')));
if($weekend != '6' && $weekend != '0'){
$new_date[] = $dateTime->format('Y-m-d');
$days--;
}
$dateTime->add(new DateInterval('P1D'));
}
return $new_date;
}
echo "<pre>";
print_r(calculateNextDate('2012-10-11', '10'));
?>
The Result would be:
Array
(
[0] => 2012-10-11
[1] => 2012-10-12
[2] => 2012-10-15
[3] => 2012-10-16
[4] => 2012-10-17
[5] => 2012-10-18
[6] => 2012-10-19
[7] => 2012-10-22
[8] => 2012-10-23
[9] => 2012-10-24
)
You can echo the date by looping the array.
Upvotes: 1
Reputation: 14492
Just substract one day first
function calculateNextDate($startDate, $days)
{
$oneDay = new DateInterval('P1D');
$dateTime = new DateTime($startDate);
$dateTime->sub($oneDay);
while($days) {
$dateTime->add($oneDay);
if ($dateTime->format('N') < 6) {
$days--;
}
}
return $dateTime->format('Y-m-d');
}
echo calculateNextDate('2012-10-01', 10);
// results in 2012-10-12
Upvotes: 1
Reputation: 606
hmm pretty complicated way to just add a days to start date
I would do this simply like this
$resultingDate = date('Y-m-d', strtotime("+$days days", $startDate));
Upvotes: 0