2012-12-25 32 views
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; 

?> 
+0

但它需要永久循环 –

+0

我会这样做的方式是1.找到第一个星期你想从$ firstDate开始的第二天2.查找从星期几(不是$ firstDate)到$ endDate的总天数3. $ total_number_of_days%7,应该是。 – kennypu

+0

@kennypu这看起来不对。如果您将一天添加到结束日期,您的过程将为结果添加1,但结果通常不应更改。 – Barmar

回答

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"; 
+0

谢谢。但为什么我的柜台仍然给我零,我已经给出了条件,如果它符合SAT,它是在1月1日它应该加一个柜台 –

+0

@GeorgeLim请看到更新的答案。 –

+0

感谢您的奥拉夫,但有一个问题,如果我将日期更改为1900年,柜台变得更小,为什么会发生?它应该给我更多的计数器 –

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已经从时代开始秒 - 日期所需的格式。

+0

嗨鲁本斯,为什么你的代码需要永远运行?我怎样才能让它更快? –

+0

@GeorgeLim对不起,我没有测试它;我会在这里尝试并编辑这些调整;等一下! – Rubens

+0

@GeorgeLim我已经添加了一个修改,请查看。 – Rubens

相关问题