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 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败