gpt4 book ai didi

php - 使php函数计算特定日期

转载 作者:可可西里 更新时间:2023-11-01 00:58:21 24 4
gpt4 key购买 nike

我有一个函数可以计算 1 年有多少天,我通过更改 $week 变量使其从星期一到星期六工作:

Monday - 6:Saturday,但当我输入 7: Sunday 时它不起作用。

谁能帮帮忙。我是否缺少任何逻辑?

$year = 2016;
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$days = array();
$i = 1;

while ($week != 7) { // here is where I change the 1-7 for days
$day++;
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
}

array_push($days,date("r", mktime(0, 0, 0, $mo,$day, $year)));
while ($newyear == $year) {
$x = strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
$i++;
if ($year == date("Y",$x)) {
array_push($days,date("r", $x));
}
$newyear = date("Y",$x);
}

print count($days);

谢谢大家的帮助加油!并且可以立即计算 2 年的总天数,例如:

我有一个日期是 2016 年 1 月 11 日,也就是星期一,我想知道从 2016 年 1 月 11 日到 2018 年 1 月 11 日有多少天,有多少个星期一。

谢谢!

最佳答案

使用 DateTime/DateInterval 函数:

$datetime1 = new DateTime('2018-01-11');
$datetime2 = new DateTime('2016-01-11');
$interval = $datetime1->diff($datetime2);
echo floor($interval->format('%a days')/7); // 104

或者使用 strtotime...

你也可以这样做:

$startDate = strtotime('2016-01-11');
$endDate = strtotime('2018-01-11');
$totalWeeks = (($endDate - $startDate)/86400)/7;
echo floor($totalWeeks); // rounds to 104

在这里阅读更多:

日期差异 - http://php.net/manual/en/datetime.diff.php

DateInterval::format - http://php.net/manual/en/dateinterval.format.php

更新...如何在计算天数时轻松“调试”它:

<?php

$startDate = strtotime('2016-01-11');
$endDate = strtotime('2018-01-11');
$currentDate = $startDate;

$count = 0;
while ($currentDate <= $endDate) {
echo date('r', $currentDate) . "\n";
$currentDate = strtotime('+1 week', $currentDate);
if ($currentDate<=$endDate) {
$count++;
}
}

echo $count . "\n";

关于php - 使php函数计算特定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34717011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com