2

Here is my code:

$graceperiod = strtotime("+30 day","23-12-2013");
echo $graceperiod;

I get the following output:

Sat, 31 Jan 1970 00:00:23 GMT

The year is wrong. Any idea why it is not converting properly?

cn007b
  • 16,596
  • 7
  • 59
  • 74
bobo2000
  • 1,779
  • 7
  • 31
  • 54
  • possible duplicate of [Add number of days to a date](http://stackoverflow.com/questions/2332681/add-number-of-days-to-a-date) – halfer Dec 22 '14 at 11:43

8 Answers8

4

strtotime is a "dangerous" function if you don't know what it does exactly. You should try it like this

strtotime('+30 days', $timestamp);

Where $timestamp is an actual timestamp, because it's not as reliable as you may wish

Jeredepp
  • 222
  • 1
  • 8
  • only works it seems when I put an actual timestamp in. – bobo2000 Dec 22 '14 at 11:39
  • It doesn't matter if you put in a timestamp or a variable filled with a timestamp as PHP is not relying on types. But a timestamp or datetype is always more reliable than a stringified representatiopn of that variable – Jeredepp Dec 22 '14 at 11:41
1

strtotime takes the Unix timestamp as its second parameter, so you need to convert it first.

The following has the correct output:

$graceperiod = date("Y-m-d", strtotime("+30 days",strtotime("23-12-2013")));
echo $graceperiod;
Antony D'Andrea
  • 991
  • 1
  • 16
  • 35
  • If you have a fixed date string like `23-12-2013`, `strtotime('23-12-2013 +30 days');` would also work. – Arc Dec 22 '14 at 11:41
1

You can either use the good old strtotime() function (which accepts a timestamp as second parameter) or use the DateTime classes:

Using strtotime()

$format = 'd-m-Y';

$timestamp = strtotime( "+30 day",strtotime( "23-12-2013" ) );
echo date( $format, $timestamp );

Using DateTime classes:

$dateTime = DateTime::createFromFormat( $format, '23-12-2013' );
$dateTime->add( new DateInterval( 'P30D' ) );
echo $dateTime->format( $format );

Here the P30D means a period of 30 days

One advantage of using DateTime is you can define your own format instead of using from the list of accepted formats for strtotime()

anp
  • 537
  • 3
  • 16
0

change

$graceperiod = strtotime("+30 day","23-12-2013");

to

$graceperiod = strtotime("+30 days","23-12-2013");

30 days is correct instead of 30 day

Reference

Pupil
  • 23,834
  • 6
  • 44
  • 66
0

strtotime takes second parammeter as timestamp, so you should do:

$graceperiod = strtotime("+30 day", strtotime("23-12-2013"));
echo date("Y-m-d H:i:s", $graceperiod);
Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30
0

Try the following code.

$date = "23-12-2013";
$graceperiod = date("Y-m-d", strtotime("+30 days",strtotime($date)));
echo $graceperiod;
Shailesh Katarmal
  • 2,757
  • 1
  • 12
  • 15
0
strtotime("next month");

or

date('Y-m-d', strtotime("+30 days"));
geekido
  • 171
  • 5
0

Code:

$graceperiod = strtotime('23-12-2013 +30 day');
var_dump(date('Y-m-d', $graceperiod));

Result:

string(10) "2014-01-22"
cn007b
  • 16,596
  • 7
  • 59
  • 74