计算一年中某一天的特定日期

时间:2012-12-25 00:00:53

标签: php date

最初我正在尝试创建一个函数来显示特定日期落入特定日期的次数。例如,星期六在特定年份的某一年的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;

?>

2 个答案:

答案 0 :(得分: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已经过了几秒钟 - 这是日期所需的格式。

答案 1 :(得分:0)

自1970-01-01以来,

strtotime为您提供。由于您只对几天感兴趣,因此您可以将循环每天增加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";