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