報表統計、週曆顯示、定時任務常需「本週週一 00:00:00」時間戳。本文提供 mondayTime() 函式:支援指定基準時間、可選回傳時間戳或格式化字串、內建靜態快取避免重複計算。
function mondayTime($timestamp = 0, $returnTimestamp = true) {
static $cache = [];
$key = $timestamp . '|' . (int)$returnTimestamp;
if (isset($cache[$key])) return $cache[$key];
if (!$timestamp) $timestamp = time();
// date('w'):0=週日, 1=週一...6=週六
$w = (int)date('w', $timestamp);
// 週一 = 當前時間 - (w-1) 天;若今天是週日(w=0),視為上週一(-6天)
$offsetDays = $w > 0 ? $w - 1 : 6;
$mondayTimestamp = strtotime("-$offsetDays days 00:00:00", $timestamp);
$result = $returnTimestamp ? $mondayTimestamp : date('Y-m-d', $mondayTimestamp);
$cache[$key] = $result;
return $result;
}
echo "本週週一時間戳: " . mondayTime() . "\n";
echo "本週週一日期: " . mondayTime(time(), false) . "\n";
echo "下週週一日期: " . mondayTime(strtotime('+1 week'), false) . "\n";
echo "指定日期所在週一: " . mondayTime(strtotime('2024-12-25'), false) . "\n"; // 2024-12-23
| 今天 date('w') | 週一偏移天數 | 說明 |
|---|---|---|
| 1 (週一) | 0 | 今天就是週一 |
| 2 (週二) | 1 | 往前 1 天 |
| 3 (週三) | 2 | 往前 2 天 |
| 4 (週四) | 3 | 往前 3 天 |
| 5 (週五) | 4 | 往前 4 天 |
| 6 (週六) | 5 | 往前 5 天 |
| 0 (週日) | 6 | 往前 6 天(屬於上週) |