核心函數:獲取指定日期所在週範圍(週一至週日)
<?php
/**
* 獲取指定日期所在週的起始/結束時間戳
* @param string|int $date 日期字串或時間戳,預設今天
* @return array ['start' => 'Y-m-d 00:00:00', 'end' => 'Y-m-d 23:59:59']
*/
function getWeekRange($date = 'today'): array {
$ts = is_numeric($date) ? (int)$date : strtotime($date);
// %u: 1=週一 ... 7=週日 (ISO-8601)
$weekDay = (int)date('N', $ts);
$startTs = $ts - ($weekDay - 1) * 86400; // 週一 00:00:00
$endTs = $startTs + 6 * 86400 + 86399; // 週日 23:59:59
return [
'start' => date('Y-m-d 00:00:00', $startTs),
'end' => date('Y-m-d 23:59:59', $endTs),
'start_ts' => $startTs,
'end_ts' => $endTs,
];
}
核心函數:獲取指定日期所在月範圍
function getMonthRange($date = 'today'): array {
$ts = is_numeric($date) ? (int)$date : strtotime($date);
$year = (int)date('Y', $ts);
$month = (int)date('m', $ts);
$daysInMonth = (int)date('t', $ts); // 當月天數
return [
'start' => "$year-$month-01 00:00:00",
'end' => "$year-$month-$daysInMonth 23:59:59",
'start_ts' => mktime(0,0,0,$month,1,$year),
'end_ts' => mktime(23,59,59,$month,$daysInMonth,$year),
];
}
高階封裝:常用範圍快捷函數
/**
* 獲取常用業務日期範圍
* @param int $type 1=昨天 2=本週 3=上週 4=上上週 5=本月 6=上月
* @return array ['start'=>..., 'end'=>..., 'start_ts'=>..., 'end_ts'=>...]
*/
function getDateRange(int $type): array {
$now = time();
switch ($type) {
case 1: // 昨天
$yesterday = strtotime('-1 day', $now);
return ['start'=>date('Y-m-d 00:00:00',$yesterday), 'end'=>date('Y-m-d 23:59:59',$yesterday)];
case 2: // 本週
return getWeekRange($now);
case 3: // 上週
return getWeekRange(strtotime('-1 week', $now));
case 4: // 上上週
return getWeekRange(strtotime('-2 weeks', $now));
case 5: // 本月
return getMonthRange($now);
case 6: // 上月
return getMonthRange(strtotime('-1 month', $now));
default:
throw new InvalidArgumentException("未知範圍類型: $type");
}
}
// 使用範例
$range = getDateRange(2); // 本週
$sql = "SELECT * FROM orders WHERE created_at BETWEEN '{$range['start']}' AND '{$range['end']}'";
echo $sql;
DateTime 現代寫法(PHP 5.3+,推薦)
function getWeekRangeDT($date = 'today'): array {
$dt = new DateTime($date);
$dt->modify('Monday this week'); // 本週週一 00:00
$start = clone $dt;
$end = clone $dt;
$end->modify('Sunday this week 23:59:59');
return ['start'=>$start->format('Y-m-d H:i:s'), 'end'=>$end->format('Y-m-d H:i:s')];
}
function getMonthRangeDT($date = 'today'): array {
$dt = new DateTime($date);
$dt->modify('first day of this month 00:00:00');
$start = clone $dt;
$end = clone $dt;
$end->modify('last day of this month 23:59:59');
return ['start'=>$start->format('Y-m-d H:i:s'), 'end'=>$end->format('Y-m-d H:i:s')];
}
時區處理關鍵點
- 資料庫儲存統一用 UTC(
SET time_zone = '+00:00')。
- PHP 腳本入口設定
date_default_timezone_set('UTC')。
- 以上函數若傳入無時區字串,會依當前腳本時區解析;傳入時間戳則為絕對時間,不受時區影響。
- 顯示給用戶時,再按用戶時區轉換(
$dt->setTimezone(new DateTimeZone($userTz)))。