首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 日期計算常用技巧總結

     編輯:PHP 相關知識

PHP 日期計算常用技巧總結

PHP 中日期時間運算主要通過 strtotime() 和 date() 函數組合實現,靈活且強大。

基礎日期運算

// 當前日期
$today = date('Y-m-d');

// 加 2 天
$twoDaysLater = date("Y-m-d", strtotime("$today + 2 days"));

// 減 1 週
$oneWeekAgo = date("Y-m-d", strtotime("$today - 1 week"));

// 下個月第一天
$nextMonthFirst = date("Y-m-01", strtotime("+1 month"));

// 本月最後一天
$lastDayOfMonth = date("Y-m-t", strtotime("$today"));

// 指定日期加減
$specificDate = '2024-01-15';
$tenDaysLater = date("Y-m-d", strtotime("$specificDate + 10 days"));

常用時間字串格式

需求strtotime 參數示例
明天+1 day / tomorrow
後天+2 days
上週一last monday
下個月+1 month / next month
去年同期-1 year
具體時間+3 hours 30 minutes

進階技巧

// 獲取時間戳
$timestamp = strtotime('2024-12-25 10:30:00');

// 格式化輸出
echo date('Y-m-d H:i:s', $timestamp);  // 2024-12-25 10:30:00
echo date('l, F j, Y', $timestamp);    // Wednesday, December 25, 2024

// 計算兩日期差值(天數)
$diff = abs(strtotime('2024-12-31') - strtotime('2024-12-01'));
$days = floor($diff / (60 * 60 * 24));  // 30 天

// 判斷是否為閏年
$isLeap = date('L', strtotime('2024-01-01'));  // 1 表示閏年

// 獲取星期幾 (0-6, 0為週日)
$weekday = date('w', strtotime('2024-12-25'));

現代替代方案:DateTime 類

PHP 5.2+ 推薦使用面向對象的 DateTime 類,功能更強大、時區處理更完善:

$date = new DateTime('2024-12-01');
$date->modify('+2 weeks');
echo $date->format('Y-m-d');  // 2024-12-15

// 時區處理
$date = new DateTime('now', new DateTimeZone('Asia/Taipei'));
echo $date->format('Y-m-d H:i:s');
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved