欢迎访问宙启技术站
智能推送

PHP日期时间函数大全,解放你的时间处理

发布时间:2023-06-10 05:01:34

在 PHP 中,时间戳可以表示为一个 Unix 时间戳(该时间戳自 “格林威治标准时间 1970 年 1 月 1 日 00:00:00” 以来的秒数),也可以表示为特定的日期格式。为了方便处理时间,PHP 提供了丰富的日期和时间函数,本文将为你介绍一些常用的日期时间函数。

一、获取时间戳

1. time() 函数:返回当前 Unix 时间戳

2. strtotime() 函数:将任何字符串的日期时间描述解析为 Unix 时间戳

例如:

strtotime('now'):返回当前时间的时间戳

strtotime('2021-07-01'):返回指定日期的时间戳(该日期的时间为 00:00:00)

二、格式化日期时间

1. date() 函数:将日期格式化成字符串

-  个参数为格式,常用的格式如下:

Y 年(4 位数)

y 年(2 位数)

m 月(01-12)

n 月(1-12)

d 日(01-31)

j 日(1-31)

H 小时(00-23)

h 小时(01-12)

G 小时(0-23)

g 小时(1-12)

i 分钟(00-59)

s 秒钟(00-59)

- 第二个参数为时间戳(可选),默认为当前时间

例如:

date('Y-m-d H:i:s'):返回当前时间的字符串表示(例如:2021-07-01 14:30:00)

date('Y-m-d H:i:s', 1625164800):将指定的时间戳格式化成字符串(例如:2021-07-01 00:00:00)

2. strftime() 函数:将本地时间/日期格式化成字符串,支持本地化(locale)设置

strftime() 函数与 date() 函数类似,但支持本地化(locale)设置。 个参数为格式,常用的格式与 date() 函数相同。在格式化日期时间时,如需按本地化格式输出,使用 %x 代替日期,使用 %X 代替时间。

例如:

setlocale(LC_TIME, 'ch_CN.UTF-8'); // 设置本地化环境

echo strftime('%Y年%m月%d日 %H时%M分%S秒'); // 输出时间字符串(例如:2021年07月01日 14时30分00秒)

三、日期时间计算

1. mktime() 函数:返回一个日期的 Unix 时间戳

mktime() 函数将指定的日期和时间转换为 Unix 时间戳。

例如:

mktime(10, 30, 0, 7, 1, 2021):返回 2021 年 7 月 1 日 10 时 30 分 0 秒的时间戳

2. strtotime() 函数:将任何字符串的日期时间描述解析为 Unix 时间戳

例如:

strtotime('+1 day'):返回明天的 Unix 时间戳

strtotime('+1 week'):返回下周的 Unix 时间戳

strtotime('-1 month'):返回上个月的 Unix 时间戳

3. date_add() 函数:将一个日期加上指定的时间间隔

date_add() 函数可以让你在日期上加上指定的时间间隔,例如:加上一天、一周、一月等。该函数需要传入两个参数: 个参数为一个 DateTime 对象,第二个参数为 DateInterval 对象。

例如:

$datetime = new DateTime('2021-07-01');

$interval = new DateInterval('P1D'); // 添加一天

date_add($datetime, $interval);

echo $datetime->format('Y-m-d'); // 输出 2021-07-02

4. date_diff() 函数:计算两个日期的时间间隔

date_diff() 函数计算两个日期之间的时间间隔。该函数需要传入两个参数,两个参数都必须是 DateTime 对象。函数返回值是一个 DateInterval 对象,该对象包含了两个日期之间的时间间隔。

例如:

$start = new DateTime('2021-07-01');

$end = new DateTime('2021-07-02');

$interval = date_diff($start, $end);

echo $interval->days; // 输出 1