2012-12-25 66 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

相關問題