douxie4583 2014-10-21 18:07
浏览 26
已采纳

添加多个间隔,直到日期为当前年份

suppose I have an initial date whose year was prior to that of the current year and I want to repeat the event every 7 days but only in the current year.

How would I find the first occurrence in the current year?

I realize I can do it with a loop like this:

$reOccurringEvent =new DateTime('2013-12-01');
$interval = new DateInterval('P7D');
while($reOccurringEvent->format('Y') < date('Y') ){
    $reOccurringEvent->add($interval);
}
echo $reOccurringEvent->format('d m Y'); //05 01 2014

But it strikes me there should be a more efficient way to achieve this rather than repeatedly adding an interval to the date (it would happen many times if the initial date was some years ago).

I was hoping to be able to calculate the number of times the interval should be added and just do it a single time.

I was thinking something like:

$date = new DateTime();
$diff = $date->diff($reOccurringEvent)->days%7;

But obviously that doesn't work and I can't quite figure out the logic of how to do it.

  • 写回答

3条回答 默认 最新

  • 普通网友 2014-10-21 19:20
    关注

    More generically, the algorithm would be to find the number of intervals between the given date and the last day of last year. Then multiplying the interval by the number of intervals + 1 to get the first interval of the current year.

    $date1="12/9/2013"; 
    $ts1 = strtotime($date1);
    $ts2 = strtotime("12/31/" . Date("Y")-1);
    
    //get the number of seconds between the date and first of the year    
    $seconds_diff = $ts2 - $ts1;
    echo "$seconds_diff <br>";
    
    //get the number of days
    $dayDiff=$seconds_diff/86400;
    
    //how many intervals?
    $intervalDays = "10";
    
    //get the number of intervals from start date to last day of last year
    $numIntervals = floor($dayDiff/$intervalDays);
    echo  $numIntervals."<br>";
    
    //now the total intervals to get into the current year is one more interval, turn this into days
    $totIntervals= ($numIntervals* $intervalDays)+$intervalDays;
    
    //Date Time date in question
    $theDt = new DateTime($date1);
    
    //Add the intervals we calculated to the date in question, and we have the first date of the interval for the current year...
    $theDt->add(new DateInterval('P' . $totIntervals. 'D'));
    
    echo "The first date of the intreval is: " . $theDt->format('Y-m-d'); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料