douweidao3882 2015-08-21 20:48
浏览 33
已采纳

PHP日期范围没有年份。 如何处理12月/ 1月环回[关闭]

I have user defined date ranges. A date range might be from November 8 - March 26 for example. I need to determine if a given date (without the year) is between one of these ranges. I don't want to include the year because the user defined date ranges are recursive for each year.

My problems is that I don't know how to handle the loop-back between December 31 and Jan 1. I'm guessing that a PHP DatePeriod object would be the way to go but how can I exclude the year from it? If I have a date range from December 10 to February 15 how can I determine if Jan 11 is in that range without specifying the year?

  • 写回答

3条回答 默认 最新

  • dongqijuan3786 2015-08-21 23:49
    关注

    If you are really not dealing with years, then making one up (as per binnyb's answer) is the way to go. The trick is adding the logic to test if the start date is after the end date - indicating that they are from different years.

    An example solution (based on the answer to a similar question with years):

    // For convenience, build MM-DD strings
    $date1 = "11-8";
    $date2 = "03-26";
    $test = "01-15";
    
    if (check_in_range($date1, $date2, $test)) echo "in range!";
    
    function check_in_range($start_date, $end_date, $test_date)
    {
        $year = '2000';
    
        $start_ts = strtotime($year.'-'.$start_date);
        $end_ts = strtotime($year.'-'.$end_date);
        $test_ts = strtotime($year.'-'.$test_date);
    
        if ($start_ts > $end_ts) {
          $year -= 1;
          $start_ts = strtotime($year.'-'.$start_date);
        }
    
        return (($test_ts >= $start_ts) && ($test_ts <= $end_ts));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c