2012-10-15 152 views
0

這樣的,我有這樣的功能:計數爲下一個非週末(週六,週日),每天給藥一開始日期和天數

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-10-01', '10'); 

這將導致:

2012-10-15 

哪個是正確的,但是我想它算$startDate作爲計數的一天,所以它會計數是這樣的:

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 

這可能嗎?

回答

1

剛。減去1天第一

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 
0

嗯相當複雜的方式只是增加一個天開始日期

我會做這個簡單的像這樣

$resultingDate = date('Y-m-d', strtotime("+$days days", $startDate)); 
+0

我忘了提,它跳過週末。 – David

1
<? 
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')); 
?> 

結果將是:

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 
) 

你可以通過循環數組來回顯日期。

相關問題