PHP 方案
方法一:strtotime 相對格式(最簡潔)
<?php
$base = '2024-01-15 10:30:00';
echo date('Y-m-d H:i:s', strtotime('-5 days', strtotime($base))); // 5 天前
echo date('Y-m-d', strtotime('+10 days')); // 10 天后
echo date('Y-m-d', strtotime('last Monday')); // 上周一
echo date('Y-m-d', strtotime('first day of +1 month')); // 下月 1 號
?>
方法二:DateTime 類(物件導向、不可變、鏈式呼叫)
<?php
use DateTime;
use DateInterval;
$dt = new DateTime('2024-01-15 10:30:00', new DateTimeZone('Asia/Shanghai'));
// 修改原物件
$dt->modify('-5 days');
echo $dt->format('Y-m-d H:i:s');
// 不可變版本 (PHP 5.5+):DateTimeImmutable
$fixed = new DateTimeImmutable('2024-01-15');
$later = $fixed->add(new DateInterval('P10D')); // 加 10 天
echo $later->format('Y-m-d');
// 計算差值
$diff = $later->diff($fixed);
echo $diff->days; // 10
echo $diff->format('%a days'); // 10 days
?>
方法三:手動計算秒數(不推薦,忽略夏令時/DST)
<?php
function subDays(int $days, int $timestamp = null): string {
$timestamp ??= time();
$past = $timestamp - $days * 86400; // 86400 秒/天
return date('Y-m-d', $past);
}
echo subDays(5); // 5 天前
// ⚠️ 跨 DST 邊界會偏移 1 小時,嚴謹場景請用 DateTime
?>
JavaScript 方案
<script>
// 現代:Intl.DateTimeFormat + Temporal (Stage 3 提案,可用 polyfill)
// 目前通用寫法:
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const today = new Date();
console.log('今天:', today.toISOString().split('T')[0]);
console.log('昨天:', addDays(today, -1).toISOString().split('T')[0]);
console.log('明天:', addDays(today, 1).toISOString().split('T')[0]);
console.log('10天前:', addDays(today, -10).toISOString().split('T')[0]);
console.log('5天后:', addDays(today, 5).toISOString().split('T')[0]);
// 格式化工具函數
function formatDate(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
console.log(formatDate(addDays(today, -1))); // 2024-01-14
</script>
時區陷阱與最佳實踐
- PHP:永遠設定
date_default_timezone_set('Asia/Shanghai') 或用 DateTimeZone
- JS:
Date 物件內部儲存 UTC,顯示時用本地時區。跨時區業務請傳 ISO 8601 字串(含時區偏移)
- 資料庫:儲存
TIMESTAMP (自動轉 UTC) 或 DATETIME (不轉換),應用層統一處理
- 跨語言傳遞:統一用
date('c') (ISO 8601) 或 Unix 時間戳 (毫秒/秒注意單位)
進階:工作日/營業日計算
<?php
function addBusinessDays(DateTimeImmutable $start, int $days): DateTimeImmutable {
$current = $start;
$added = 0;
while ($added < $days) {
$current = $current->add(new DateInterval('P1D'));
$w = (int)$current->format('N'); // 1=Mon ... 7=Sun
if ($w < 6) $added++; // 排除週六日
}
return $current;
}
$start = new DateTimeImmutable('2024-01-15'); // 星期一
echo addBusinessDays($start, 5)->format('Y-m-d'); // 2024-01-22 (跳過週末)
?>