<?php
$date1 = strtotime('2011-04-30'); // 目標日期轉時間戳
$date2 = time(); // 當前時間戳
$now = strftime("%Y年-%m月-%d日", $date2);
$target = strftime("%Y年-%m月-%d日", $date1);
$days = round(($date1 - $date2) / 86400);
echo "今天是<font color='red'>$now</font><br>";
echo "距 $target 還有<font color='red'>$days</font>天";
?>
<?php
echo date("Y-m-d H:i:s", strtotime("now")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("10 September 2000")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("+2 day")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("+1 week")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("+1 week 2 days 4 hours 2 seconds")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("next Thursday")) . "<br>";
echo date("Y-m-d H:i:s", strtotime("last Monday")) . "<br>";
// 指定基準時間
echo date("Y-m-d H:i:s", strtotime("+3 day", strtotime('2001-01-01')));
?>
DateTime 物件導向、支援時區、避免 2038 年問題:
<?php
$today = new DateTime('now', new DateTimeZone('Asia/Taipei'));
$target = new DateTime('2011-04-30', new DateTimeZone('Asia/Taipei'));
$interval = $today->diff($target); // 回傳 DateInterval 物件
$days = $interval->days; // 總天數(正數)
// 判斷過去/未來
$invert = $interval->invert; // 1=目標在過去, 0=目標在未來
echo "今天:" . $today->format('Y年m月d日') . "<br>";
echo "目標:" . $target->format('Y年m月d日') . "<br>";
echo "相差:$days 天" . ($invert ? "(已過)" : "(剩餘)");
?>
| 格式 | 說明 |
|---|---|
+1 day | 明天 |
-1 week | 一週前 |
first day of this month | 本月第一天 |
last day of next month | 下個月最後一天 |
next Friday | 下一個星期五 |
last day of February 2024 | 2024 年 2 月最後一天 |
strtotime() 回傳 false 於解析失敗時,務必檢查。00-69 視為 2000-2069,70-99 視為 1970-1999。DateTime + DateTimeZone。