PHP 中的 strtotime 函数可以将一个日期时间字符串转换为 Unix 时间戳。
PHP strtotime函数详解
什么是 strtotime 函数?
PHP 中的 strtotime
函数可以将一个日期时间字符串转换为 Unix 时间戳。
函数语法
strtotime ( string $time [, int $now = time() ] ) : int
$time
:必需,待转换为 Unix 时间戳的时间字符串。$now
:可选,返回一个将被用作 now 的 Unix 时间戳。
函数返回值
函数返回转换后的 Unix 时间戳,如果转换失败,则返回 false。
函数使用方法
对于 strtotime
函数,我们可以使用具体时间字符串或时间戳作为参数。
<?php
// 将时间字符串转换为 Unix 时间戳
$time_str = "2020-05-15 12:30:45";
$timestamp = strtotime($time_str);
echo $timestamp;
// 将时间戳转换为格式化时间字符串
$time_str2 = date("Y-m-d H:i:s", $timestamp);
echo $time_str2;
?>
上面的代码将输出:
1589519445
2020-05-15 12:30:45
你还可以进行各种时间计算,比如获取 N 天之后的时间、获取当前时间、获取上个月最后一天的时间等。
获取 N 天之后的时间
<?php
// 获取 3 天后的时间戳
$timestamp = strtotime("+3 day");
echo $timestamp;
// 获取 3 天后的时间字符串
$time_str = date("Y-m-d H:i:s", $timestamp);
echo $time_str;
?>
上面的代码将输出:
1590004249
2020-05-21 15:24:09
获取当前时间
<?php
// 获取当前时间的 Unix 时间戳
$current_timestamp = time();
echo $current_timestamp;
// 获取当前时间的格式化字符串
$current_time_str = date("Y-m-d H:i:s", $current_timestamp);
echo $current_time_str;
?>
上面的代码将输出:
1589773385
2020-05-18 10:23:05
总结
strtotime
函数是 PHP 中非常实用的函数,它可以将时间字符串转换为 Unix 时间戳,也可以进行各种时间计算,使用起来非常方便。在编写 PHP 代码时,建议多加使用。
沃梦达教程
本文标题为:PHP strtotime函数详解
猜你喜欢
- PHP序列化的四种实现方法与横向对比 2022-11-28
- PDO::getAvailableDrivers讲解 2022-12-08
- php中try catch捕获异常实例详解 2023-04-25
- PHP swoole中使用task进程异步的处理耗时任务应用案例分析 2023-04-02
- PHP实现简单注册登录详细代码 2023-05-09
- php双向队列实例讲解 2022-09-11
- php设计模式之原型模式分析【星际争霸游戏案例】 2023-04-02
- PHP实现的操作数组类库定义与用法示例 2023-01-15
- php实现的rc4加密解密类定义与用法示例 2022-11-08
- PHP保姆级API制作教程,不会剁手 2022-09-02