views:

63

answers:

3

Hello!

How can I get what date it will be after 31 days starting with $startDate, where $startDate is a string of this format: YYYYMMDD.

Thank you.

+5  A: 

strtotime will give you a Unix timestamp:

$date = '20101007';
$newDate = strtotime($date.' + 31 days');

you can then use date to format that into the same format, if that's what you need:

echo date('Ymd', $newDate);
Tim Fountain
Thank you, Tim. Is that the "best" way of doing this? I'm a bit worried about the `+31 days` part.
Francisc
You just need to be conscious of what format `$date` is in; if you keep it in a standard format, you're fine - if you try to parse arbitrary formats (eg dd/mm/yyyy vs mm/dd/yyyy) you could run into problems. Pick one, make sure it works, and then enforce that format for all dates you use.
mway
Thank you, mway.
Francisc
+1  A: 

Just a note that +1 month will also work if you want the same date on the next month and not 31 days exactly each time.

tandu
+1  A: 

If you're using PHP 5.3:

$date = new DateTime('20101007');
$date->add(new DateInterval('P31D');
echo $date->format('Y-m-d');

The pre-5.3 date functions are lacking, to say the least. The DateTime stuff makes it much easier to deal with dates. http://us3.php.net/manual/en/book.datetime.php

bradym
Thank you, bradym.
Francisc