简体   繁体   English

PHP-计算日期范围内的Le日

[英]PHP - Counting Leap Days in Date Range

I am trying to count the number of leap days within a date range. 我正在尝试计算日期范围内的leap日数。

This is what I have so far (adopted code from here ) 这就是我到目前为止(从这里通过的代码)

<?php
$date_from = strtotime('2019-06-01');
$date_to = strtotime('2021-05-30');
$leapday_count = 0;

for($year=$date_from; $year<=$date_to; $year=strtotime('next year', $year)) {

    if (date('L', $year)) {
         $leapday_count++;
    }   

}

echo $leapday_count;
?>

Here is what I need help with: 这是我需要帮助的:

  1. The above code does only look at the years of the start and end date. 上面的代码仅查看开始日期和结束日期的年份。 For example it does not take into consideration if the start date is after Feb 29th. 例如,如果开始日期在2月29日之后,则不会考虑。 How can I make sure that it really takes the entire dates into consideration and not only the years of the dates? 我如何确保它确实考虑了整个日期,而不仅仅是日期的年份?

    • Example expected result: 0 leap days between 2020-03-01 2024-02-28 预期结果示例:2020-03-01 2024-02-28之间的0天
    • Example expected result: 2 leap days between 2020-02-28 2024-03-01 预期结果示例:2020-02-28 2024-03-01之间的2个leap日

Thanks in advance! 提前致谢!

Stop doing date maths. 停止做日期数学。 It's hard. 这个很难(硬。

Use datetime and diff 使用日期时间和差异

http://php.net/manual/en/datetime.diff.php http://php.net/manual/en/datetime.diff.php

Example there 那里的例子

$datetime1 = new DateTime('2009-10-11');

$datetime2 = new DateTime('2009-10-13');

$interval = $datetime1->diff($datetime2);

 echo $interval->format('%R%a days');

to exactly answer the question. 准确回答问题。

$start = new DateTime('2020-03-01');
$end = new DateTime('2024-02-28');
$interval = ("last day of feb next year");

$current = clone $start;
$leapYears = 0;
while ($current->modify("last day of feb") && $current <= $end) {
    if ($current->format('d') == 29 && $current > $start) {
        $leapYears++;
    }
    $current->modify("+1 year");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM