strtotime 奇怪的行为时 - 登录偏移量
strtotime weird behaviour when - sign in offset
来自下面一行-
$date = strtotime('-' . (-100) . ' years');
当我在我的本地代码上尝试这个时,我得到了一个值 4654765319
。在实时站点上尝试时,同一行给出的值 $date
与 NULL
相同。此行不包含任何变量,因此没有其他代码影响它。
如果我删除减号 - 即
,我会在本地和实时中得到正确的值
$date = strtotime('-' . (100) . ' years');
在两种情况下给出相同的输出 -1656664323
。
谁能弄清楚为什么 strtotime()
在两个带有 -
符号的平台上表现不同?
谢谢。
您很可能 运行 是 PHP 的 32 位版本。来自 PHP documentation 的注释:
The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)
您可以改为使用 PHP 的 DateTime
class:
$date = new DateTime();
$date->modify('-' . (-100) . ' years');
echo $date->format('U');
这里是问题的清晰再现:
<?php
echo '-' . (-100) . ' years'."\n";
echo '-' . (100) . ' years'."\n";
会打印出来
--100 years
-100 years
第一个显然是一个错误的日期字符串,strtotime man page 表示函数将 return FALSE
作为结果,看起来像 NULL
,所以您的现场网站工作正常。我不知道为什么你的本地机器不会给出相同的结果 - 比较两台机器之间的配置 - 它们 运行 相同 O/S 和版本吗?
George 在下面发表评论后,我在我的 64 位机器上写了一个更完整的测试程序:
<?php
echo '-' . (-100) . ' years'."\n";
echo '-' . (100) . ' years'."\n";
echo ($d1=strtotime('-' . (-100) . ' years'))."\n";
echo ($d2=strtotime('-' . (100) . ' years'))."\n";
echo date('Y-m-d',$d1)."\n";
echo date('Y-m-d',$d2)."\n";
打印出来
--100 years
-100 years
4654771244
-1656662356
2117-07-03
1917-07-03
我以前从未尝试过,但显然 strtotime()
将 --100
解释为 -(-100)
即 +100
- 所以我要说你的 live 站点运行不正常,可能是因为它是 32 位环境。
来自下面一行-
$date = strtotime('-' . (-100) . ' years');
当我在我的本地代码上尝试这个时,我得到了一个值 4654765319
。在实时站点上尝试时,同一行给出的值 $date
与 NULL
相同。此行不包含任何变量,因此没有其他代码影响它。
如果我删除减号 - 即
,我会在本地和实时中得到正确的值$date = strtotime('-' . (100) . ' years');
在两种情况下给出相同的输出 -1656664323
。
谁能弄清楚为什么 strtotime()
在两个带有 -
符号的平台上表现不同?
谢谢。
您很可能 运行 是 PHP 的 32 位版本。来自 PHP documentation 的注释:
The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)
您可以改为使用 PHP 的 DateTime
class:
$date = new DateTime();
$date->modify('-' . (-100) . ' years');
echo $date->format('U');
这里是问题的清晰再现:
<?php
echo '-' . (-100) . ' years'."\n";
echo '-' . (100) . ' years'."\n";
会打印出来
--100 years
-100 years
第一个显然是一个错误的日期字符串,strtotime man page 表示函数将 return FALSE
作为结果,看起来像 NULL
,所以您的现场网站工作正常。我不知道为什么你的本地机器不会给出相同的结果 - 比较两台机器之间的配置 - 它们 运行 相同 O/S 和版本吗?
George 在下面发表评论后,我在我的 64 位机器上写了一个更完整的测试程序:
<?php
echo '-' . (-100) . ' years'."\n";
echo '-' . (100) . ' years'."\n";
echo ($d1=strtotime('-' . (-100) . ' years'))."\n";
echo ($d2=strtotime('-' . (100) . ' years'))."\n";
echo date('Y-m-d',$d1)."\n";
echo date('Y-m-d',$d2)."\n";
打印出来
--100 years
-100 years
4654771244
-1656662356
2117-07-03
1917-07-03
我以前从未尝试过,但显然 strtotime()
将 --100
解释为 -(-100)
即 +100
- 所以我要说你的 live 站点运行不正常,可能是因为它是 32 位环境。