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

PHP的strtotime()函数:将字符串转换为日期和时间

发布时间:2023-06-24 16:57:24

在PHP中,strtotime() 函数是将字符串转换为日期或时间戳的常用函数之一。日期和时间是计算机中常见的数据类型,对于Web开发人员来说,使用PHP来处理日期和时间时是非常有用的。这个函数可以将一些常见的日期时间格式的字符串(例如 "10 September 2021" 、 "2021-09-10" 和 "10-09-2021 12:00:00" 等)转换成时间戳或日期对象。

函数的语法如下:

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

个参数 $time 是需要转换成日期或时间戳的字符串。第二个参数 $now 是可选参数,指定要用作当前时间的时间戳。如果未传入 $now 参数,则默认使用当前系统的时间戳。

函数的返回值为 Unix 时间戳,如果字符串格式不正确,则返回 false

例如:

$time = "2021-09-10";
$timestamp = strtotime($time);

echo $timestamp; // 1631230800

在上面的例子中,传入了一个日期的字符串 $time(即 "2021-09-10"),strtotime() 函数将其转换为 Unix 时间戳,$timestamp 存储着转换后的结果。

在下面,我们介绍一些常见的时间格式和如何使用 strtotime() 函数将它们转换为日期或时间戳。

### 转换日期格式

Unix 时间戳是以秒为单位计算的从 1970 年 1 月 1 日零时零分零秒 到指定时刻的秒数。strtotime() 函数可以接收一些通用的日期格式,例如:

- "2010-01-10"( YYYY-MM-DD )

- "10 january 2022" ( d Monthname YYYY )

- "Feb 10,2022" ( M DD,YYYY )

@tip

注意,传递字符串时, 始终使用英文单词作为月份名称,因为某些语言的月份名称可能会导致日期无法正确解析。

例如:

$date1 = "2010-01-10";
$date2 = "10 january 2022";
$date3 = "Feb 10,2022";

$timestamp1 = strtotime($date1); // 1263062400
$timestamp2 = strtotime($date2); // 1641782400
$timestamp3 = strtotime($date3); // 1644460800

在上面的例子中,strtotime() 函数将不同格式的日期字符串转换为时间戳。这些时间戳将表示从 1970 年 1 月 1 日零时零分零秒 到每个日期的秒数。

### 转换时间格式

strtotime() 函数可以自动解析一些常见的时间格式。例如:

- "10:30am" ( h:i a )

- "22:45"( H:i )

- "15:30:20" ( H:i:s )

例如:

$time1 = "10:30am";
$time2 = "22:45";
$time3 = "15:30:20";

$timestamp1 = strtotime($time1); // 1631242200
$timestamp2 = strtotime($time2); // 1631288700
$timestamp3 = strtotime($time3); // 1631267420

在上面的例子中,strtotime() 函数自动解析不同格式的时间字符串并将其转换为 Unix 时间戳。这些时间戳将表示从 1970 年 1 月 1 日零时零分零秒 到每个时间的秒数。

### 转换相对时间

除了日期和时间格式之外,strtotime() 还可以解析相对日期和时间。例如:

- "+1 day"

- "-1 month"

- "+2 years"

- "next Thursday"

- "last Friday"

例如:

$date = "+1 day";
$timestamp = strtotime($date); // 1631317200

在上面的例子中,strtotime() 函数将 "+1 day" 转换为当前日期后一天的时间戳。

### 时间跨度

在PHP中,时间跨度是一个有用的概念。时间跨度是指从一个日期时间到另一个日期时间之间经历了多长时间。在时间跨度的计算中,可以使用 strtotime() 函数计算两个日期时间之间的秒数。

例如:

$start = strtotime("2022-01-01 12:00:00");
$end = strtotime("2022-01-02 13:00:00");
$diff = $end - $start;

echo $diff; // 86400

在上面的例子中,我们计算了从 2022 年 1 月 1 日中午 12:00:00 到 2022 年 1 月 2 日中午 1:00:00 总共经过了多少秒。我们使用 strtotime() 函数将两个日期时间字符串转换为时间戳,然后使用数学减法计算它们之间的秒数。

最后,strtotime() 的一个常见用法是将用户输入的日期和时间字符串格式化为所需的格式,以便在数据库或应用程序中进行存储和处理。通过使用该函数,我们可以轻松地将多种不同格式的日期和时间字符串转换为 Unix 时间戳或日期对象,使我们能够更好地处理和管理这些数据。