douhu8851 2017-01-05 20:04
浏览 32
已采纳

PHP会在一周内检查两个日期以进行倒计时

I have two events on two days each week. Both starting on 13:15 at each day. Each tuesday and each thursday. I need to check if the nearest event (from now()) is tuesday (till 13:15) OR thursday (till 13:15) to set the javascript countdown correctly (it will get the date("Y-m-d H:i:s") string for counting)

PSEUDO EXAMPLE:

if( tuesday("13:15") == 'over' &&  thursday("13:15") == 'remaining' ) {
  echo 'Next event start thursday 13:15'; 
  // need time format here for the thursday
} else {
  echo 'Next event start tuesday 13:15'; 
  // need time format here for the tuesday
}

I'm struggling with comparing the time ranges:

$now = new DateTime(date("Y-m-d"));

$event_time = '13:15';
$event_tuesday = new DateTime("next tuesday");
$event_thursday = new DateTime("next thursday");

echo $diff_tuesday = $event_tuesday->diff($now)->format("%a");
echo $diff_thursday = $event_thursday->diff($now)->format("%a");

But i think that's anyway wrong. Can somebody give me a hint?

  • 写回答

2条回答 默认 最新

  • drzfnr0275 2017-01-05 20:14
    关注

    You can use the power of PHP's strtotime which understands strings like next Tuesday, next month + 1 day, etc.

    Please see comments in the following code snippet.

    Please also note that you must set the default timezone as appropriate.

    // Current instant:
    $now = time();
    
    // 13:15 of today's day if it's Tuesday (regardless of the current time), 
    // otherwise the next upcoming Tuesday:
    $thisTuesday1315 = strtotime("this Tuesday 13:15");
    
    // 13:15 of today's day if it's Thursday (regardless of the current time), 
    // otherwise the next upcoming Thursday:
    $thisThursday1315 = strtotime("this Thursday 13:15");
    
    if($thisTuesday1315 <= $now || ($now < $thisThursday1315 && $thisThursday1315 < $thisTuesday1315)) {
        echo 'Next event start: Thursday 13:15';
        // You may use the `$thisThursday1315` timestamp here
    } else {
        echo 'Next event start: Tuesday 13:15';
        // You may use the `$thisTuesday1315` timestamp here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号