Php 向日期添加年份将重置为1970-01-01

Php 向日期添加年份将重置为1970-01-01,php,date,strtotime,dateadd,Php,Date,Strtotime,Dateadd,输出 $somedate = "1980-02-15"; $otherdate = strtotime('+1 year', strtotime($somedate)); echo date('Y-m-d', $otherdate); $somedate = "1980-02-15"; $otherdate = strtotime('+2 year', strtotime($somedate)); echo date('Y-m-d', $otherdate); $somedate = "1

输出

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

输出

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

输出

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

如何修复?

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

这就像y2k一样,由于32位限制,系统无法处理该年之后的日期。使用解决此问题的

适用于PHP 5.3+

1970-01-01
适用于PHP 5.2

$date = new DateTime('1980-02-15');
$date->add(new DateInterval('P75Y'));
echo $date->format('Y-m-d');
strotime()使用unix时间戳,因此如果它试图计算2038年之后的年份,并返回到1970年,则会溢出

要解决这个问题,请使用DateTime对象。

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

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

对于unix时间戳,最大可表示时间为2038-01-19。协调世界时03时14分07分


因此,您不能使用时间戳来表示/操作时间。

PHP的日期限制在1970年1月1日到2038年1月19日之间。您必须使用不同的方法来处理日期


PEAR有一个日期类:

如何使用datetime类为给定的字符串“1980-02-15”添加75年?谢谢。我得到一个致命错误:调用未定义的函数date\u add()。我使用的是PHP版本5.2.17.Ahh。这需要5.3。让我看看我是否能找到一个5.2的例子。好的,找到了一个PHP 5.2的替代方案。如何使用datetime类为给定的字符串“1980-02-15”添加75年?谢谢。我得到一个致命错误:调用未定义的方法DateTime::add()。我使用的是PHP版本5.2.17.::add仅在5.3+中。您需要使用字符串参数调用::modify,该参数与strotime使用的参数类似。