萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP strtotime() 計算今日與指定日期相差天數

核心邏輯

  1. 將兩個日期轉為 Unix 時間戳(秒數)。
  2. 相減得到秒數差。
  3. 除以 86400(一天秒數)並四捨五入。

基本範例

<?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>天";
?>

strtotime() 相對日期格式大全

<?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 類別(PHP 5.2+)

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 20242024 年 2 月最後一天

注意事項

  • strtotime() 回傳 false 於解析失敗時,務必檢查。
  • 兩位數年份:00-69 視為 2000-2069,70-99 視為 1970-1999。
  • 跨時區計算請改用 DateTime + DateTimeZone。
copyright © 萬盛學電腦網 all rights reserved