Checking if there's a leap day in a timerange

前端 未结 2 1394

How to check if there is a February 29th in between 2 timestamps?

$date_from = \'2007-06-01\';
$date_to = \'2013-05-30\';

I know in this ra

相关标签:
2条回答
  • 2020-12-20 10:01

    This will loop through the years, but it is even easier after you find a leap year because the next one will be 4 years after, etc.

    $date_from = strtotime('2007-06-01');
    $date_to = strtotime('2013-05-30');
    
    for($year=$date_from; $year<=$date_to; $year=strtotime('next year', $year)) {
        echo date('Y', $year);
        echo date('L', $year) ? 'Leap year' : 'Not leap year';
    }
    

    But I think you can just check if the year 'Y' is evenly divisible by 4.

    0 讨论(0)
  • 2020-12-20 10:01

    The problem I had was I wanted to find if Feb 29 existed in a smaller date range. It assumes that there is not more than two years. This my solution for that:

    $startDate = strtotime('2015-10-01 00:00:00');
    $endDate = strtotime('2016-09-30 23:00:00');
    $feb29StartYear = mktime(0, 0, 0, 2, 29, date('Y', $startDate));
    $feb29EndYear = mktime(0, 0, 0, 2, 29, date('Y', $endDate));
    
    if( (date('L', $startDate) && $startDate < $feb29StartYear) || 
        (date('L', $endDate) && $endDate > $feb29EndYear)) { //We have a leap day
         //some logic here
    }
    

    Just thought this may be useful for someone else.

    0 讨论(0)
提交回复
热议问题