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

如何使用PHP的strtotime函数进行时间转换?

发布时间:2023-06-14 06:19:59

strtotime函数是PHP中的日期和时间函数,用于将人类可读的日期字符串转换为UNIX时间戳。UNIX时间戳是从1970年1月1日0时0分0秒UTC(协调世界时)起经过的秒数。

strtotime函数非常有用,可以将日期字符串转换为UNIX时间戳,然后可以进行各种日期计算和格式化输出。在本篇文章中,我们将研究如何使用strtotime函数进行时间转换。

1. 基本语法

strtotime函数有一个参数,即需要转换的日期字符串。基本语法如下:

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

- $time:需要转换的日期字符串

- $now:可选参数,指定指定转换日期的基准时间,如果省略,则默认为当前时间

返回值为UNIX时间戳;如果转换失败,则返回false。

2. 常见的日期字符串格式

strtotime函数支持许多不同的日期字符串格式。以下是常见的日期字符串格式:

- now:当前时间

- +1 day:相对于当前时间加一天

- +2 weeks:相对于当前时间加两周

- +1 month:相对于当前时间加一个月

- +1 year:相对于当前时间加一年

- 2018-02-28:指定的年、月、日

- 2/3/2018:月/日/年

- 2.3.2018:月.日.年

- February 28 2018:月 日 年

- 28 February 2018:日 月 年

- Feb 28 2018:月 日 年

- 28 Feb 2018:日 月 年

- 2018-02-28 12:34:56:指定的年、月、日、小时、分钟和秒

- 2018/02/28 12:34:56:斜线分隔的年、月、日、小时、分钟和秒

- 2018.02.28 12:34:56:小数点分隔的年、月、日、小时、分钟和秒

3. 实例

我们来看几个实例,来展示如何使用strtotime函数进行时间转换:

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

$time_str = '2018-02-28 12:34:56';
$time_stamp = strtotime($time_str);
echo $time_stamp;   // 输出: 1519809296

2. 相对于当前时间加一小时

$time_str = '+1 hour';
$time_stamp = strtotime($time_str);
echo $time_stamp;   // 输出: 1638343412

3. 相对于指定的日期加一周

$time_str = '2020-01-01';
$time_stamp = strtotime($time_str . ' +1 week');
echo $time_stamp;   // 输出: 1578412800

4. 自定义格式化输出

$time_str = '2020-05-01 02:45:12';
$time_stamp = strtotime($time_str);
$date = date('Y年m月d日 H:i:s', $time_stamp);
echo $date;   // 输出: 2020年05月01日 02:45:12

以上这些例子展示了如何使用strtotime函数进行时间转换。PHP的strtotime函数非常灵活,可以帮助我们处理各种时间操作和计算。了解strtotime函数如何使用,将对我们的开发工作非常有帮助。