2011-01-14 110 views
0

PHP計算周是週日 - 週六嗎?對於給定的日期,我試圖確定本週的開始和結束日期以及下一週/前幾周的開始日期。一切都可以正常工作,除非我在星期天通過,它認爲日期在前一週。計算指定日期的星期

$start = $_GET['start']; 
$year = date('Y', strtotime($start)); 
$week = date('W', strtotime($start)); 
$sunday = strtotime($year.'W'.$week.'0'); 

$next = strtotime('+7 Days', $sunday); 
$prev = strtotime('-7 Days', $sunday); 

echo '<p>week: ' . $week . '</p>'; 
echo '<p>sunday: ' . date('Y-m-d', $sunday) . '</p>'; 
echo '<p>next:' . date('Y-m-d', $next) . '</p>'; 
echo '<p>prev: ' . date('Y-m-d', $prev) . '</p>'; 

結果:

2011-01-09 (Sunday) 
Week: 01 
WRONG 

2011-01-10 (Monday) 
Week: 02 
RIGHT 

2011-01-15 (Saturday) 
Week: 02 
RIGHT 

回答

2

PHP根本不會考慮數週,如果你得到錯誤的結果,那是因爲你的數學是關閉的。 :)

$date = strtotime('2011-1-14'); 
$startingSunday = strtotime('-' . date('w', $date) . ' days', $date); 
$previousSaturday = strtotime('-1 day', $startingSunday); 
$nextWeekSunday = strtotime('+7 days', $startingSunday); 
1

如ISO_8601定義,指的是什麼date('W'),一個星期開始與週一

但要小心,並閱讀了ISO-周:http://en.wikipedia.org/wiki/ISO_week_date

也許結果並不總是像預期。

例如:

date('W',mktime(0, 0, 0, 1, 1, 2011)) 

它會返回52,而不是01,因爲一年的第一個ISO周是第一週,在給定的每年至少4天。
由於2011-1-1是星期六,因此只有2天,所以2011-1-1是2010年最後一週(52)的ISO,而不是2011年的第一週。

+0

感謝對於有用的信息,我認爲現在的問題更清晰 – 2011-01-14 03:25:09

2

正如Dr.Molle指出的那樣,關於「W」的信息是正確的。你的問題在這裏:

$sunday = strtotime($year.'W'.$week.'0'); 
$sunday = strtotime($year.'W'.$week.'0'); 

$next = strtotime('+7 Days', $sunday); 
$prev = strtotime('-7 Days', $sunday); 

然後你在Timestamp對象上調用strtotime(對不起,我不知道確切的術語)。

錯誤的參數類型(時間戳和字符串使用不正確)是問題的原因。這裏是我的一段代碼,以確定一週和一週的開始日:

<?php 
$date = '2011/09/09'; 

while (date('w', strtotime($date)) != 1) { 

    $tmp = strtotime('-1 day', strtotime($date)); 
    $date = date('Y-m-d', $tmp); 

} 

$week = date('W', strtotime($date)); 

echo '<p>week: ' . $week . '</p>'; 

?> 

爲了充分了解,你應該看看上date & strtotime手冊。

1

函數日期('W')使用ISO-8601定義,因此星期一是一週中的第一天。

代替日期('W')使用strftime('%U')。

實施例:

$date = strtotime('2011-01-09'); 
echo strftime('%U',$date); 

結果:

02 

的代碼:

$date = strtotime('2012-05-06'); 
$sunday = date('Y-m-d', strtotime(strftime("%Y-W%U-0", $date))); 
$sturday = date('Y-m-d', strtotime(strftime("%Y-W%U-6", $date))); 
echo $sunday . "\n"; 
echo $saturday; 

結果:

2012-05-06 
2012-05-12 
+0

非常感謝,我一直在學習英語,不要再寫錯了。 – 2012-10-30 00:02:04

相關問題