PHP Date

Date function reference: format, parse, timestamps, timezones.

Intermediate
Key PointsUse `DateTime` in new code; the procedural API appears mostly in legacy.

Function overview

FunctionPurposeExample
date格式化时间戳date("Y-m-d")
time当前时间戳1700000000
mktime由时分秒月日年造时间戳mktime(0,0,0,11,15,2023)
strtotime解析时间描述strtotime("+1 day")
checkdate日期是否真实存在checkdate(2,30,2023) → false
date_diff两个日期之差返回 DateInterval
date_add日期加区间date_add($d, $i)
getdate拆成关联数组["year"]、["mon"]

Examples

PHP
<?php
date_default_timezone_set("Asia/Shanghai");

$ts = mktime(0, 0, 0, 11, 15, 2023);
echo $ts, "\n";
echo date("Y-m-d H:i:s", $ts), "\n";
echo date("Y-m-d", strtotime("+7 days", $ts)), "\n";

var_dump(checkdate(2, 30, 2023));
var_dump(checkdate(2, 29, 2024));

$d = getdate($ts);
echo $d["year"] . "-" . $d["mon"] . "-" . $d["mday"], "\n";
echo $d["weekday"], "\n";
Output
1700006400
2023-11-15 00:00:00
2023-11-22
bool(false)
bool(true)
2023-11-15
Wednesday

mktime takes hour, minute, second, month, day, year — not year-first. The most commonly misremembered argument order in PHP.

Date difference

PHP
<?php
$a = new DateTime("2023-11-15");
$b = new DateTime("2024-02-20");

$diff = $a->diff($b);
echo $diff->days, "\n";
echo $diff->format("%y 年 %m 月 %d 天"), "\n";
echo $diff->invert, "\n";

$d2 = $b->diff($a);
echo $d2->invert, "\n";
Output
97
0 年 3 月 5 天
0
1

invert is 1 when the result is negative (the second date precedes the first). **Never judge order from days** — it is always positive.

Timestamp boundaries

PHP
<?php
date_default_timezone_set("Asia/Shanghai");

// 当天零点与次日零点
$today = strtotime("today");
$tomorrow = strtotime("tomorrow");

echo date("Y-m-d H:i:s", $today), "\n";
echo date("Y-m-d H:i:s", $tomorrow), "\n";
echo ($tomorrow - $today) / 3600, "\n";

// 本月最后一天
echo date("Y-m-t", $today), "\n";

// 本周一
echo date("Y-m-d", strtotime("monday this week", $today)), "\n";
Output
2023-11-15 00:00:00
2023-11-16 00:00:00
24
2023-11-30
2023-11-13
On DST transitions tomorrow-minus-today is not 24 hours. China has no DST, but multi-timezone systems must not assume 86400 seconds per day.

Friends & Partners