1

最初我试图创建一个函数来显示特定日期有多少次进入特定日期。例如星期六有多少次落在某年的 1 月 1 日到某年。

<?php 

$firstDate = '01/01/2000';
$endDate = '01/01/2012';
$newYearDate= '01/01';

# convert above string to time
$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);
$newYearTime = strtotime($newYearDate);

for($i=$time1; $i<=$time2; $i++){
    $saturday = 0;
    $chk = date('D', $newYearTime); #date conversion
   if($chk == 'Sat' && $chk == $newYearTime){ 
      $saturday++;    
      } 
}
echo $saturday;

?>
4

2 回答 2

1

你只能有一个星期六,比如 1 月 1 日,一年一次,所以:

$firstDate = '01/01/2000';
$endDate = '01/01/2012';

$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);

$saturday = 0;
while ($time1 < $time2) {

    $time1 = strtotime(date("Y-m-d", $time1) . " +1 year");
    $chk = date('D', $time1);
    if ($chk == 'Sat') {
        $saturday++;
    }

}

echo "Saturdays at 01/01/yyyy: " . $saturday . "\n";

我更改的行是:

$time1 = strtotime(date("Y-m-d", strtotime($time1)) . " +1 year");

$time1 = strtotime(date("Y-m-d", $time1) . " +1 year");

$time1从纪元开始已经以秒为单位——日期所需的格式。

于 2012-12-25T00:34:39.037 回答
0

strtotime自 1970-01-01 以来为您提供秒数。由于您只对天感兴趣,因此您可以每天将循环增加 86400 秒以加快计算速度

for($i = $time1; $i <= $time2; $i += 86400) {
...
}

有几点

  • 移出$saturday你的循环
  • 检查除夕与一年中的某一天
  • 检查循环计数器$i而不是$newYearTime

这应该工作

$firstDate = '01/01/2000';
$endDate = '01/01/2012';

# convert above string to time
$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);

$saturday = 0;
for($i=$time1; $i<=$time2; $i += 86400){
    $weekday = date('D', $i);
    $dayofyear = date('z', $i);
    if($weekday == 'Sat' && $dayofyear == 0){ 
        $saturday++;    
    } 
}

echo "$saturday\n";
于 2012-12-25T00:24:01.777 回答