strtotime

(PHP 4, PHP 5, PHP 7, PHP 8)

strtotime将任何字符串的日期时间描述解析为 Unix 时间戳

说明

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

本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 Unix 时间戳(自 January 1 1970 00:00:00 UTC 起的秒数),其值相对于 now 参数给出的时间,如果没有提供 now 参数则用系统当前时间。

警告

本函数返回的 Unix 时间戳不包含时区信息,为了实现对 "日期/时间" 进行计算,推荐使用功能更强大的 DateTimeImmutable 类。

本函数将使用 TZ 环境变量(如果有的话)来计算时间戳。自 PHP 5.1.0 起有更容易的方法来定义时区用于所有的日期/时间函数。此过程在 date_default_timezone_get() 函数页面中有说明。

参数

datetime

日期/时间字符串。正确格式的说明详见 日期与时间格式

now

用来计算返回值的时间戳。

返回值

成功则返回时间戳,否则返回 false。在 PHP 5.1.0 之前本函数在失败时返回 -1

错误/异常

在每 次调用日期/时间函数时,如果时区无效则会引发 E_NOTICE 错误,如果使用系统设定值或 TZ 环境变量,则会引发 E_STRICTE_WARNING 消息。参见 date_default_timezone_set()

范例

示例 #1 strtotime() 例子

<?php
echo strtotime("now"), "\n";
echo 
strtotime("10 September 2000"), "\n";
echo 
strtotime("+1 day"), "\n";
echo 
strtotime("+1 week"), "\n";
echo 
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo 
strtotime("next Thursday"), "\n";
echo 
strtotime("last Monday"), "\n";
?>

示例 #2 失败检查

<?php
$str 
'Not Good';

// PHP 5.1.0 之前的版本中和应该改成和 -1 进行比较
if (($timestamp strtotime($str)) === false) {
    echo 
"The string ($str) is bogus";
} else {
    echo 
"$str == " date('l dS of F Y h:i:s A'$timestamp);
}
?>

注释

注意:

如果给定的年份是两位数字的格式,则其值 0-69 表示 2000-2069,70-100 表示 1970-2000。 See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).

注意:

有效的时间戳通常从 Fri, 13 Dec 1901 20:45:54 UTC 到 Tue, 19 Jan 2038 03:14:07 UTC(对应于 32 位有符号整数的最小值和最大值)。

PHP 5.1.0 之前,不是所有的平台都支持负的时间戳,那么日记范围就被限制为不能早于 Unix 纪元。这意味着在 1970 年 1 月 1 日之前的日期将不能用在 Windows,一些 Linux 版本,以及几个其它的操作系统中。

在 64 位的 PHP 版本中,时间戳的有效范围实际上是无限的,因为 64 位可以覆盖最多 2930 亿年的范围。

注意:

不同的分隔符,比如 m/d/yd-m-y 会影响到解析结果:若以反斜线 (/) 为分隔,将会做为美洲日期 m/d/y 来解析;而当分隔符为短横线 (-) 或点 (.) 时,则将做为欧洲日期 d-m-y 格式来解析。当年份只有两位数字,且分隔符为短横线 (-时,日期字符串将被解析为 y-m-d 格式。

为了避免潜在的歧义,最好使用 ISO 8601 标准格式 (YYYY-MM-DD) 或 DateTime::createFromFormat() 来表达。

注意:

不建议使用此函数对日期进行数学运算。在 PHP 5.3 及以后版本中,推荐使用 DateTime::add()DateTime::sub() 函数,PHP 5.2 中可以使用 DateTime::modify()

参见