3

我有一个计算一年中有多少天的函数,我通过将$week变量从以下更改为从星期一到星期六工作:

Monday - 6:SaturdaySunday,但是当我放 7:时它不起作用

任何人都可以帮忙。我错过了任何逻辑吗?

$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 日有多少天,有多少个星期一。

谢谢你!

4

2 回答 2

3

使用 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

在这里阅读更多:

DateDiff - 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";
于 2016-01-11T08:53:39.183 回答
2
$date_1 =  strtotime("2016-01-11");
$date_2 = strtotime("2018-01-11");
$datediff = $date_2 - $date_1;
echo floor($datediff/(60*60*24));

修改的 :

您可以在两个日期之间找到一周中的任何一天。只需更改 $days[0] 的值;

星期一:

<?php
$date_1 = $from = strtotime('2016-01-11');
$date_2 = strtotime('2018-01-11');
$days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
$count = 0;
while ($date_1 < $date_2) {
  if(date('l', $date_1) == $days[0]);
  {
    $count++;   
  }
  $date_1 += 7 * 24 * 3600;
}
echo "From : ".date('Y-m-d',$from)."  To : ".date('Y-m-d',$date_2)."  has $count  $days[0]";
?>

输出 :

From : 2016-01-11 To : 2018-01-11 has 105 Monday
于 2016-01-11T09:12:00.383 回答