计算自年初以来的天数时出错

Error calculating the number of days since the start of the year

我正在尝试计算自特定日期以来的天数,但在第 87 天出现错误,并持续到第 303 天,然后 returns 恢复正常。错误总是低于十进制数 .958333333333.

function findDays($day, $month) {return   ( (mktime(0, 0, 1, $month, $day)-strtotime("2022-01-01 00:00:01"))/86400)+1;}


$months=[31,28,31,30,31,30,31,31,30,31,30,31]; 
for($i=0;$i<12;$i++){ 
    echo "<br>month-".($i+1).": ";
    for($j=0;$j<$months[$i];$j++){
        $days= findDays($j+1, $i+1);
        echo $days." | ";
    } 
}

如果您只想知道某个特定日期自年初以来经过了多少天,您可以使用日期格式:

function findDays($day, $month) {
    return DateTime::createFromFormat('m-d', $month . '-' . $day)
               ->format('z');
}

对于今天,2022 年 4 月 1 日,returns90(如果您不提供 DateTime 格式的年份,则使用当前年份)。

如果你想得到从特定日期开始的天数,你可以使用 DateInterval:

function findDays($day, $month) {
    $baseDate = new DateTime("2020-01-01");

    return DateTime::createFromFormat('m-d', $month . '-' . $day)
               ->diff($baseDate)
               ->days;
}

今天,returns 自 2020 年 1 月 1 日以来已经过去了 821 天。