time():取得當前 Unix 時間戳(秒)strtotime($datetime, $baseTimestamp):解析英文文字日期時間描述為 Unix 時間戳date($format, $timestamp):格式化時間戳為字串| 輸入字串 | 含義 | 範例輸出 |
|---|---|---|
| now | 現在 | 當前時間戳 |
| +1 day | 明天這時 | +86400 秒 |
| -1 day | 昨天這時 | -86400 秒 |
| +1 week | 下週這時 | +604800 秒 |
| +1 week 2 days 4 hours 2 seconds | 組合相對時間 | 依序疊加 |
| next Thursday | 下個星期四 00:00 | 下週四凌晨 |
| last Monday | 上個星期一 00:00 | 上週一凌晨 |
| first day of this month | 本月 1 號 00:00 | 月首 |
| last day of next month | 下月最後一天 23:59:59 | 月末 |
| 2023-12-25 | 指定日期(ISO 8601) | 該日 00:00 |
| 2023-12-25 14:30:00 | 指定日期時間 | 該時刻 |
echo strtotime("now") . "\n";
echo strtotime("10 September 2000") . "\n";
echo strtotime("+1 day") . "\n";
echo strtotime("+1 week") . "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds") . "\n";
echo strtotime("next Thursday") . "\n";
echo strtotime("last Monday") . "\n";
// 格式化輸出
echo date("Y-m-d H:i:s", time()) . "\n"; // 當前
echo date("Y-m-d H:i:s", strtotime("+1 day")) . "\n"; // 明天
echo date("Y-m-d H:i:s", strtotime("-1 day")) . "\n"; // 昨天
echo date("Y-m-d H:i:s", strtotime("+1 week")) . "\n"; // 下週
echo date("Y-m-d H:i:s", strtotime("-1 week")) . "\n"; // 上週
echo date("Y-m-d H:i:s", strtotime("next Thursday")) . "\n";// 下週四
echo date("Y-m-d H:i:s", strtotime("last Thursday")) . "\n";// 上週四
// 字串格式建議用 ISO 8601 (YYYY-MM-DD) 避免歧義
$ts = strtotime('2023-12-25'); // 2023-12-25 00:00:00
$ts = strtotime('2023-12-25 14:30:00');
// 1 月 31 日執行
echo date('Y-m-d', strtotime('+1 month')); // 3 月 3 日(非 2 月 31 日)
// 建議用:
echo date('Y-m-d', strtotime('first day of +1 month')); // 2 月 1 日
// 腳本開頭設定時區(預設 UTC)
date_default_timezone_set('Asia/Taipei'); // 或 Asia/Shanghai
// 或 php.ini: date.timezone = Asia/Taipei
32 位元 PHP 整數最大值約 2038-01-19,超過會溢位。現代環境請使用 64 位元 PHP 或 DateTime 類別。
$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));
$dt->modify('+1 week');
echo $dt->format('Y-m-d H:i:s');
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', '2023-12-25 14:30:00');
echo $dt2->getTimestamp(); // 取得時間戳
time() 比 strtotime('now') 快(無解析開銷)。DateTime 物件複用,避免重複建立。NOW(), DATE_ADD() 等函數,減少應用層運算。