2016-05-27 20 views
6

我想弄清楚如何計算經常性週期的給定日期後的最近日期。如何計算給定日期(PHP)後的經常性週期的最近日期

例如,如果經常性週期爲每兩週,從2016年1月1日開始,且給定日期爲1月17日,那麼我如何計算下一個經常性週期日期是1月28日?

經常性期限可以是任意天數,數週,數月或數年。

現在我能想到的唯一解決方案是從開始日期和循環開始,在每次迭代中添加循環週期,直到我通過給定日期,但我想知道是否有更高效或優雅的解決方案?

+1

看起來像一個重複:http://stackoverflow.com/questions/32151998/php-find-next-future-recurring-date – Arcesilas

回答

0

如果您打開並且不介意數據庫選項和迷你cron腳本,我有一個建議。創建一個稱爲recurring_track表,並有一個鍵值列:

對於如:

last_recurring_period爲鍵和值是2016年5月25日

現在運行cron腳本每次都只是更新經常性持續時間發生。

現在您只需查詢此表以瞭解什麼是最近一次的經常性週期,現在什麼時候可以添加和確定給定日期的下一個經常性週期。

4

您可以使用DatePeriod來完成它:

$begin = new DateTime('2016-01-01'); 
$end = new DateTime('2016-12-31'); 
$interval = new DateInterval('P14D'); 
$datePeriod = new DatePeriod($begin, $interval ,$end); 

$givenDate = new DateTime('2016-01-17'); 

foreach ($datePeriod as $date) { 
    if ($date < $givenDate) { 
     continue; 
    } 

    echo 'The next recurring period date is ' . $date->format('Y-m-d'); 
    break; 
} 

輸出將是:

下一個再現週期的日期是2016年1月29日

0

試試這個,

$starting_dat = '2016-01-01'; 
    $recurring_prd = "2 week"; 
    $given_dat = '2016-02-28'; 

    while ($given_dat > $starting_dat) 
    { 


      $next_date=date('Y-m-d', strtotime($recurring_prd, strtotime(date($starting_dat)))); 
      $starting_dat = $next_date; 
    } 

    echo date('d-m-Y', strtotime($next_date)); 
+0

這基本上是我想知道是否有更好的解決方案循環因爲如果我理解正確! –

0
$now = time(); // or your date as well 
$your_date = strtotime("2010-01-01"); 

//Get difference in days 
$datediff = $now - $your_date; // in days say 60 days 

//use mod with your reoccurring period 
$remain = $datediff % $recPeriod // her say 2 weeks = 14 days recurring gets you 4 
//nearest recured date 
$recdate = strtotime("-".$remain." day", $now); // 4 days ago 

Modify similar way for next date too 
+0

這是一個很好的解決方案,但不能運行數月或數年,沒有一致的'$ recPeriod' –

0

相反循環你可以做一些數學,並充分利用DateTime類的:

$start = new DateTime("2016-01-01"); 
$interval = 14; 

$current = new DateTime("2016-01-17"); 

// Here we subtract from the interval (14 days) the amount of days remaining 
// to the next recurring date 
$daysUntilNext = $interval - ($current->diff($start)->days % $interval); 

$next = $current->modify("+$daysUntilNext days"); 

// $next now contains the next recurring date 
+0

這是一個很好的解決方案,但不能運行數月或數年,沒有一致的'$ interval' –

+0

「一致的$間隔」是什麼意思? DateTime ::修改照顧,你實際上得到一個有效的日期,所以它不會給你2016-01-35什麼的。 –

+0

我的意思是說,如果間隔是(例如)每個月,有些月份是28(或29)天,有些是30,有些是31.同樣多年(當有閏年時) –

0

另取此,相當類似於從@Matei米哈伊之一,但不要求內進行檢查最終循環。感覺應該有更好的方法將DateInterval的多個實例添加到DateTime中。

<?php 
$start = new DateTime('2016-01-01'); 
$cutOff = new DateTime('2016-01-17'); 
$period = new DateInterval('P2W'); 

// Find out the total number of complete periods between the two dates 
$distance = $start->diff($cutOff)->days; 
$periodsBetween = (int) ($distance/$period->d); 

// Then add on that number of periods + 1 to the original date 
for ($a=1; $a<=$periodsBetween + 1; $a++) 
{ 
    $start->add($period); 
} 

echo $start->format('Y-m-d'); // 2016-01-29 
相關問題