简体   繁体   中英

Add years to todays date in php

I'm getting a weird date ('01/01/1970 00:00:00) when I run the following code in php:

$now = date('d/m/Y H:i:s', time());
$exp = date('d/m/Y H:i:s', strtotime($now .'+100 years'));

I would try something like this

$date = new DateTime();
$exp = $date->modify('+100 years')->format('d/m/Y H:i:s');

Try following one.

$now = date('d/m/Y H:i:s', strtotime('+100 years'));

Output => 26/06/2117 18:58:07

Try this code :

<?php
$year = date('Y-m-d H:i:s', strtotime('+5 years'));
echo $year;
?>

Output:

2022-06-26 13:29:07

Try this

date('d/m/Y H:i:s', strtotime('+100 years'));

Output :-

26/06/2117 09:31:15

It because you're giving the wrong date format for this function strtotime($now .'+100 years') and it returns false .

try that:

echo date('d/m/Y H:i:s', strtotime("+100 year"));

"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.)"

http://php.net/manual/en/function.strtotime.php

$d = date('Y-m-d', strtotime('+5 years'));

You're apparently falling into one or both the following problems:

  1. a simple formatting issue (this is wrong for sure) where, since you're using / as separator, strtotime interprets days as months and vice-versa; as you can read in the documentation page for strtotime ( Notes paragraph) :

Dates in the m/d/y or dmy formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European dmy format is assumed

This can be easily fixed by changing your first line from:

$now = date('d\m\Y H:i:s', time());

to:

$now = date('d-m-Y H:i:s', time());
  1. the Year 2038 Problem . You can read about this too, in the same documentation page (same paragraph, right above the previous quote):

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)

If that's your case, you better use DateTime objects (as others suggested here ), which do not suffer this limitation. Here's a line which should work:

$exp = date_format(date_create("+100 years"), 'd/m/Y H:i:s');

What is happening in your code is that:

  • since you're passing a non-existing date (and maybe because of a 32-bit environment too), strtotime returns false
  • when passing false to the second argument of the date function, which expects an int , false is cast to 0 , which makes date return the Epoch Time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM