dsfykqq3403 2015-08-22 03:33
浏览 21

PHP - 找到下一个未来的重复日期?

I have a database of events that are both "static" (on a specific day) and "recurring" (starting on a specific day, but set to be "recurring" either every week or every other week). I understand that there needs to be intervals of 7 and 14, but I don't know how to get to that point to find a date > today and spit it out.

so example;

I want to find the next upcoming recurring events and spit out their relevant dates. Side note: the data I'm stuck working with is in strings (I know, I know) of Ymd so 20150821 would be Aug 21st 2015.

if today was Aug 21 2015 and there's a recurring event for "Every other Friday" starting on Aug 7, it would be +14 which would get you to today, Friday Aug 21.

But say there was one for "Every Wednesday" starting Aug 19, I'd want to get the date for Wednesday, Aug 26 and spit that out.

This would need to work for infinite dates in the future, with the start dates never changing.

So running the script on Jan 1 2016, I'd need to know that the next "Every Wednesday" was Jan 6 2016.

pseudo code:

if(start_date < today_date) {
    // start date is in the past
    add recurring_inverval to start_date until result >= today_date
    echo result
} elseif(start_date > today_date {
    // start date is in the future
    echo start_date
}

it's the adding until x that I'm lost at. not sure how to do that within an if statement.

also not sure if that's the best way to go about it. I know PHP can also do complicated strings and convert them to a date. like "Next Saturday"

  • 写回答

2条回答 默认 最新

  • duan1443 2015-08-22 03:55
    关注

    solved it myself:

    $begin = new DateTime($start_date); // start searching on the start date of the event
    $end = new DateTime(date('Ymd')); // end on today's date
    $end = $end->modify('+1 month'); // extend search to the next month
    
    $interval = new DateInterval('P'. $freq_math .'D'); // intervals of Plus X Days - uses frequency math of 7 or 14 for every or every other
    $daterange = new DatePeriod($begin, $interval, $end);
    
    
    foreach($daterange as $date) {
        if($date->format('Ymd') >= date('Ymd')) {
            $next_recurring_date = $date->format('Ymd');
            break;
        }
    }
    
    echo $next_recurring_date;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突