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

使用PHP的strtotime()函数将日期时间字符串转换为UNIX时间戳

发布时间:2023-06-14 06:20:52

在开发Web应用程序时,我们经常需要将日期和时间转换为UNIX时间戳。UNIX时间戳是从1970年1月1日00:00:00 UTC以来经过的秒数。PHP提供了一个函数strtotime(),可以将日期时间字符串转换为UNIX时间戳。

strtotime()函数的语法是:

strtotime ( string $time [, int $now ] ) : int|false

其中,$time是待转换为UNIX时间戳的日期和/或时间字符串;$now是可选参数,指定时间参考点。如果$now未提供,则PHP将使用当前时间作为参考点。如果转换成功,则该函数将返回时间戳,否则将返回false。

strtotime()函数支持大多数常见格式的日期和时间字符串,包括:

- YYYY-MM-DD

- YYYY/MM/DD

- M/D/YY

- MM-DD-YYYY

- MM/DD/YYYY

- Month DD, YYYY

- Weekday Month DD YYYY HH:MM:SS

- NEXT MONDAY

- LAST DAY OF THIS MONTH

- 2 WEEKS AGO

示例:

1. 将'2021-10-01 12:00:00'转换为UNIX时间戳:

$date = '2021-10-01 12:00:00';
$timestamp = strtotime($date);
echo $timestamp;

输出:

1633089600

2. 将'October 1, 2021'转换为UNIX时间戳:

$date = 'October 1, 2021';
$timestamp = strtotime($date);
echo $timestamp;

输出:

1633046400

3. 将'next Friday 3pm'转换为UNIX时间戳:

$date = 'next Friday 3pm';
$timestamp = strtotime($date);
echo $timestamp;

输出:

1634067600

需要注意的是,strtotime()函数是基于所在服务器的时区设置进行转换的。如果需要在特定时区进行转换,可以使用date_default_timezone_set()函数设置默认时区。

示例:

// 设置时区为纽约
date_default_timezone_set('America/New_York');

$date = '2021-10-01 12:00:00';
$timestamp = strtotime($date);
echo $timestamp;

输出:

1633096800

总之,strtotime()函数是PHP中非常有用的日期和时间处理函数,可以将各种日期时间格式转换为UNIX时间戳,并轻松进行各种操作。