制作 php 函数来计算特定日期

making php functions to count specific day

我有一个函数可以计算 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

日期间隔::格式 - http://php.net/manual/en/dateinterval.format.php

更新...如何'debug'轻松地计算天数:

<?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";
$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