在PHP中,可以使用内置的日期时间函数来处理日期和时间。PHP中最常用的日期时间函数是date()函数,用于格式化日期和时间。
除了date()函数外,PHP还支持以下常用日期时间函数:
date()函数需要两个参数:第一个参数是日期时间格式,第二个参数是可选的时间戳。如果不指定时间戳,则默认使用当前时间戳。以下是一些常用的日期时间格式:
Format | Description | Example
----------|------------------------------------------------------------|----------------------
d | Day of the month, 2 digits with leading zeros | 01 to 31
D | A textual representation of a day, three letters | Mon through Sun
m | Month, 2 digits with leading zeros | 01 to 12
M | A short textual representation of a month, three letters | Jan through Dec
y | Year, 2 digits | 00 to 99
Y | Year, 4 digits | 0000 to 9999
H | Hour in 24-hour format, 2 digits with leading zeros | 00 to 23
h | Hour in 12-hour format, 2 digits with leading zeros | 01 to 12
i | Minutes, 2 digits with leading zeros | 00 to 59
s | Seconds, 2 digits with leading zeros | 00 to 59
a | Lowercase Ante meridiem and Post meridiem | am or pm
A | Uppercase Ante meridiem and Post meridiem | AM or PM
例如,要将时间戳转换为格式为“Y-m-d H:i:s”的日期时间字符串,可以使用以下代码:
$timestamp = time();
$date = date('Y-m-d H:i:s', $timestamp);
echo $date;
输出结果可能类似于“2021-07-22 12:34:56”。