Find out if date is between two dates, ignoring year

前端 未结 4 1287
孤城傲影
孤城傲影 2021-01-18 12:20

I need to determine if a date (month and day) is between two other month/days.

I\'ve attached an image to this post that describes what I\'m trying to do. Basically

4条回答
  •  长情又很酷
    2021-01-18 13:09

    To solve this, you can convert your dates to 4-digit numbers of the form MMDD.

    $start = '1122';
    $end = '0315';
    $date = '0201';
    

    If you don't yet have your dates formatted like this, you can use date('md', $timestamp), or just calculate the number by taking $month * 100 + $day;

    Then your test logic will change depending on whether you're crossing a year boundary or not. Putting it all together, it might look like this:

    function isDateBetween($testM, $testD, $startM, $startD, $endM, $endD) {
        $start = $startM*100 + $startD;
        $end = $endM*100 + $endD;
        $date = $testM*100 + $testD;
    
        if ($start > $end) {
            // crossing a year boundary
            return ($date > $start) || ($date < $end);
        } else {
            // not crossing a year
            return ($date > $start) && ($date < $end);
        }
    }
    

    Here's some examples of calling this function:

    // your example given above
    isDateBetween(2, 1, 11, 22, 3, 15); // true
    
    // ends the day after instead
    isDateBetween(3, 16, 11, 22, 3, 15); // false
    
    // reverse the dates in your example
    isDateBetween(2, 1, 3, 15, 11, 22); // false
    
    // ends the day after, with reversed dates
    isDateBetween(3, 16, 3, 15, 11, 22); // true 
    

提交回复
热议问题