Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

php - Adding years to a date resets to 1970-01-01

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

outputs

1981-02-15

and

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

outputs

1982-02-15

but

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

outputs

1970-01-01

How to fix?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's the 2038 bug which is like y2k where systems can't handle dates after that year due to 32 bit limitations. Use the DateTime class instead which does work around this issue.

For PHP 5.3+

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

For PHP 5.2

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...