将年份添加到日期会重置为1970-01-01

问题描述 投票:3回答:5
$somedate = "1980-02-15";
$otherdate = strtotime('+1 year', strtotime($somedate));
echo date('Y-m-d', $otherdate);

输出

1981-02-15

$somedate = "1980-02-15";
$otherdate = strtotime('+2 year', strtotime($somedate));
echo date('Y-m-d', $otherdate); 

输出

1982-02-15

$somedate = "1980-02-15";
$otherdate = strtotime('+75 year', strtotime($somedate));
echo date('Y-m-d', $otherdate); 

输出

1970-01-01

怎么修?

php date strtotime dateadd
5个回答
5
投票

这是2038 bug,就像y2k一样,由于32位的限制,系统无法在那一年之后处理日期。使用DateTime class代替哪个可以解决这个问题。

适用于PHP 5.3+

$date = new DateTime('1980-02-15');
$date->add(new DateInterval('P75Y'));
echo $date->format('Y-m-d');

对于PHP 5.2

$date = new DateTime('1980-02-15');
$date->modify('+75 year');
echo $date->format('Y-m-d');

3
投票

strtotime()使用unix时间戳,因此如果它试图计算2038年以后的年份并恢复到1970年,它就会溢出。

要解决此问题,请使用DateTime对象。 http://php.net/manual/en/book.datetime.php

要向DateTime对象添加一段时间,请使用DateTime :: add,它将DateInterval作为参数。 http://php.net/manual/en/datetime.add.php http://www.php.net/manual/en/class.dateinterval.php

$date = new DateTime("1980-02-15");
if (method_exists("DateTime", "add")) {
    $date->add(new DateInterval("Y75"));
} else {
    $date->modify("+75 years");
}
echo $date->format("Y-m-d");

1
投票

对于unix时间戳,最大可表示时间为2038-01-19。上午03:14:07 UTC

因此,您无法使用时间戳表示/操作时间。


1
投票

PHP的日期限制在01-01-1970至19-01-2038之间。您将不得不使用不同的方法来处理日期。

PEAR有一个Date类:PEAR Date


0
投票

从1980年起的75年是2055年,它超过了可以用32位整数表示的最高日期值。因此,结果变为0,这是您观察到的1970年。

© www.soinside.com 2019 - 2024. All rights reserved.