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

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

发布时间:2023-06-21 00:39:17

strtotime函数是PHP内置的一个日期时间函数,用于将翻译为英文的日期时间描述字符串转换为UNIX时间戳。UNIX时间戳是一个整数值,表示从1970年1月1日00:00:00 UTC起到指定日期时间的秒数。

strtotime函数的用法非常简单,它只接受一个字符串参数,返回一个整数值,表示从1970年1月1日00:00:00 UTC起到指定日期时间的秒数。以下是strtotime函数的基本语法:

int strtotime(string $time, int $now = time())

其中,$time是待转换的日期时间字符串,$now是参考时间。如果省略$now参数,函数将以当前系统时间为参考时间。

strtotime函数支持的日期时间字符串格式非常丰富,下面是一些常见的格式:

1. 纯数字日期格式,如"2022-05-18",表示2022年5月18日。

2. 数字日期和时间格式,如"2022-05-18 10:30:00",表示2022年5月18日10点30分。

3. 相对日期时间格式,如"now"表示当前时间,"tomorrow"表示明天。

4. 英文描述的日期时间格式,如"next monday"表示下周一。

下面是一些具体的使用示例:

1. 将纯数字日期字符串转换为UNIX时间戳

$time = '2022-05-18';
$timestamp = strtotime($time);
echo $timestamp; // 输出: 1652880000

2. 将数字日期时间字符串转换为UNIX时间戳

$time = '2022-05-18 10:30:00';
$timestamp = strtotime($time);
echo $timestamp; // 输出: 1652928600

3. 将相对时间字符串转换为UNIX时间戳

$time = 'next monday';
$timestamp = strtotime($time);
echo $timestamp; // 输出: 1653398400

4. 使用$now参数指定参考时间

$time = '+1 day';
$now = strtotime('2022-05-18 10:30:00');
$timestamp = strtotime($time, $now);
echo $timestamp; // 输出:1653010200

在使用strtotime函数时需要注意以下几点:

1. strtotime函数无法识别所有的日期时间格式,特别是中文日期格式,因此要确保日期时间字符串格式符合函数要求。

2. strtotime函数对于一些不规范的日期时间描述字符串可能会返回不合理的UNIX时间戳,因此需要进行有效的检查和校验。

3. strtotime函数返回的UNIX时间戳是一个整数值,如果需要将其转换为可读的日期时间格式,可以使用date函数进行格式化输出。

通过使用strtotime函数,我们可以方便地将日期时间字符串转换为UNIX时间戳,从而进行日期时间的计算和处理。在实际开发中,需要根据具体需求选择合适的日期时间格式,使用strtotime函数进行转换,并进行有效的数据校验和格式化输出。