使用PHP的strtotime函数将日期/时间字符串转换为时间戳
发布时间:2023-05-28 21:56:15
strtotime是一个用于将日期/时间字符串转换为时间戳的PHP函数。时间戳是表示日期和时间的整数,它表示从1970年1月1日00:00:00 UTC(协调世界时)开始到指定时刻的秒数。 strtotime函数将日期/时间字符串作为参数,并返回与该字符串相应的时间戳。
strtotime函数可以接受各种不同格式的日期/时间字符串作为参数,包括以下几种常见格式:
- Y-m-d H:i:s:年-月-日 时:分:秒
- Y/m/d H:i:s:年/月/日 时:分:秒
- Y-m-d:年-月-日
- Y/m/d:年/月/日
- H:i:s:时:分:秒
除了上述格式之外,strtotime函数还可以处理相对时间字符串。例如,您可以将“+1 day”传递给函数,以获取当前时间24小时后的时间戳。
以下是使用strtotime函数将日期/时间字符串转换为时间戳的示例:
$date_string = '2022-04-01 12:00:00'; $timestamp = strtotime($date_string); echo $timestamp; // 输出:1648845600 $date_string = '2022/04/01 12:00:00'; $timestamp = strtotime($date_string); echo $timestamp; // 输出:1648845600 $date_string = '2022-04-01'; $timestamp = strtotime($date_string); echo $timestamp; // 输出:1648759200 $date_string = '+1 day'; $timestamp = strtotime($date_string); echo $timestamp; // 输出:当前时间24小时后的时间戳
值得注意的是,strtotime函数返回的时间戳是基于服务器的时区设置的。如果您需要将时间戳转换为另一个时区的日期/时间字符串,请使用date函数。
总之,strtotime函数是一个方便的PHP函数,它允许开发者以各种不同的格式将日期/时间字符串转换为时间戳。它的用途广泛,可用于各种类型的应用程序。
