萬盛學電腦網

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

PHP 日期時間處理大全:Unix 時間戳、格式化、計算、驗證、時區與日曆生成實例

Unix 時間戳

Unix Timestamp 為從 1970-01-01 00:00:00 UTC 起經過的秒數,是跨平台、跨資料庫的時間通用格式。

字串轉時間戳

strtotime() - 自然語言解析

<?php
echo strtotime('2009-03-05');           // 1236211200
echo strtotime('2009-03-05 10:24:30');  // 1236248670
echo strtotime('10 September 2000');    // 968544000
echo strtotime('next Monday');          // 下個星期一
echo strtotime('+1 week');              // 一週後
?>

mktime() - 組合元件產生時間戳

<?php
// 時, 分, 秒, 月, 日, 年
$ts = mktime(10, 24, 30, 3, 5, 2009); // 2009-03-05 10:24:30
?>

時間戳格式化輸出:date()

<?php
echo date('Y-m-d H:i:s');      // 2024-05-20 14:30:00
echo date('Y/m/d');            // 2024/05/20
echo date('l, F j, Y');        // Monday, May 20, 2024
echo date('c');                // ISO 8601: 2024-05-20T14:30:00+08:00
echo date('r');                // RFC 2822: Mon, 20 May 2024 14:30:00 +0800
?>

常用格式字元速查表

字元說明範例
Y4 位數年份2024
y2 位數年份24
m月份(前導零)05
n月份(無前導零)5
d日期(前導零)20
j日期(無前導零)20
H24 小時(前導零)14
G24 小時(無前導零)14
h12 小時(前導零)02
g12 小時(無前導零)2
i分鐘(前導零)30
s秒數(前導零)00
l星期完整名稱Monday
D星期縮寫Mon
w星期數字(0=Sun)1
t當月總天數31
L是否閏年1/0
UUnix 時間戳1716201000

getdate() - 取得日期時間陣列

<?php
$arr = getdate();
print_r($arr);
/*
Array
(
    [seconds] => 30
    [minutes] => 30
    [hours]   => 14
    [mday]    => 20
    [wday]    => 1
    [mon]     => 5
    [year]    => 2024
    [yday]    => 140
    [weekday] => Monday
    [month]   => May
    [0]       => 1716201000
)
*/
?>

日期計算與驗證

兩日期相差天數

<?php
$start = mktime(0,0,0, 9, 24, 2008);
$end   = mktime(0,0,0, 10, 12, 2008);
$days  = ($end - $start) / (24*3600);
echo $days; // 18
?>

checkdate() 驗證日期合法性

<?php
var_dump(checkdate(12, 31, 2000)); // bool(true)
var_dump(checkdate(2, 29, 2001));  // bool(false) 非閏年
?>

時區設定

<?php
// 設定預設時區(建議放在腳本最開頭或 php.ini)
date_default_timezone_set('Asia/Taipei');  // 台灣
// date_default_timezone_set('PRC');       // 中國大陸
// date_default_timezone_set('Asia/Shanghai');
// date_default_timezone_set('UTC');       // 國際標準時間

echo date('Y-m-d H:i:s'); // 現在會顯示正確本地時間
?>

實戰範例:動態月曆生成

<?php
$year  = isset($_GET['year'])  ? (int)$_GET['year']  : date('Y');
$month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$today = date('j');

// 邊界檢查
$year  = max(1970, min(2037, $year));
$month = max(1, min(12, $month));

// 導航連結
$prevYear  = $year - 1;
$nextYear  = $year + 1;
$prevMonth = $month - 1 ?: 12;
$nextMonth = $month + 1 > 12 ? 1 : $month;
$prevYearLink  = $prevMonth == 12 ? $prevYear : $year;
$nextYearLink  = $nextMonth == 1  ? $nextYear : $year;

// 當月第一天星期幾 (0=Sun)
$firstWeekday = date('w', mktime(0,0,0, $month, 1, $year));
// 當月總天數
$daysInMonth = date('t', mktime(0,0,0, $month, 1, $year));

$weekLabels = ['日','一','二','三','四','五','六'];
?>
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse; width:100%; max-width:400px;">
  <tr style="background:#eee;">
    <td colspan="4"><a href="?year=&month=><</a>  年 <a href="?year=&month=>></a></td>
    <td colspan="3"><a href="?year=&month=><</a>  月 <a href="?year=&month=>></a></td>
  </tr>
  <tr style="text-align:center;">
    
      <th></th>
    
  </tr>
  <tr style="text-align:center;">
    
  </tr>
</table>

現代替代方案:DateTime 類別

PHP 5.2+ 建議使用物件導向的 DateTime、DateTimeImmutable、DateInterval、DatePeriod,功能更強大、時區處理更直觀:

<?php
$dt = new DateTime('2024-05-20 14:30:00', new DateTimeZone('Asia/Taipei'));
echo $dt->format('Y-m-d H:i:s');
$dt->add(new DateInterval('P1M')); // 加一個月
echo $dt->format('Y-m-d');
$diff = $dt->diff(new DateTime('2024-01-01'));
echo $diff->days . ' 天';
?>
copyright © 萬盛學電腦網 all rights reserved