<?php
$date = new DateTime();
$date->modify('this week'); // 本週一
$firstDay = $date->format('Y-m-d');
$date->modify('this week +6 days'); // 本週日
$lastDay = $date->format('Y-m-d');
echo "本週一:$firstDay\n";
echo "本週日:$lastDay\n";
?>
注意:modify('this week') 在 PHP 不同版本行為可能不一,建議搭配 modify('monday this week') 明確指定。
<?php
/**
* 取得指定時間戳所在週的週一
* @param int $timestamp 時間戳,預設現在
* @param bool $asTimestamp 是否回傳時間戳,否則回傳 Y-m-d 字串
*/
function thisMonday($timestamp = 0, $asTimestamp = true) {
static $cache = [];
$key = $timestamp . $asTimestamp;
if (!isset($cache[$key])) {
$timestamp = $timestamp ?: time();
// date('w'):0=週日, 1=週一...6=週六
$w = (int)date('w', $timestamp);
// 計算差異天數:週一為基準
$diff = $w === 0 ? -6 : 1 - $w; // 週日視為上週結束
$monday = $timestamp + $diff * 86400;
$cache[$key] = $asTimestamp ? $monday : date('Y-m-d', $monday);
}
return $cache[$key];
}
/** 取得本週週日 */
function thisSunday($timestamp = 0, $asTimestamp = true) {
$monday = thisMonday($timestamp, true);
$sunday = $monday + 6 * 86400;
return $asTimestamp ? $sunday : date('Y-m-d', $sunday);
}
// 使用範例
echo '本週一:' . thisMonday(0, false) . PHP_EOL;
echo '本週日:' . thisSunday(0, false) . PHP_EOL;
echo '下週一:' . thisMonday(strtotime('+1 week'), false) . PHP_EOL;
?>
<?php
// PHP 5.3.3+ 較穩定
$monday = date('Y-m-d', strtotime('monday this week'));
$sunday = date('Y-m-d', strtotime('sunday this week'));
// 或指定基準時間
$monday = date('Y-m-d', strtotime('monday', $timestamp));
$sunday = date('Y-m-d', strtotime('sunday', $timestamp));
?>
| 方法 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| DateTime::modify | 物件導向、可鏈式調用、時區處理完善 | 較舊版本 'this week' 行為不一 | 現代專案、需時區處理 |
| 時間戳運算 | 效能最好、行為確定、可快取 | 需自行處理邏輯 | 高頻呼叫、舊版本相容 |
| strtotime 相對字串 | 程式碼最簡潔 | 舊版本解析差異大 | 快速原型、PHP 5.4+ |
<?php
$mondayTs = thisMonday();
$sundayTs = thisSunday();
$sql = "SELECT * FROM reports
WHERE created_at >= FROM_UNIXTIME($mondayTs)
AND created_at < FROM_UNIXTIME($sundayTs + 86400)
ORDER BY created_at DESC";
?>