Tag Archives: strtotime

PHP: How to Add Days, Months or Years to a Date Programming 14 MAY 2012

Date work is always icky, but luckily PHP has some pretty nifty functions that can pretty much do all the heavy lifting for you.

One of most commonly faced problems is how to add either a number of days, months or years to a given date, and thanks to PHP’s fantastic strtotime function and its natural language (well sort of) parsing, this becomes pretty trivial to solve.

Taken from the PHP manual: The strtotime function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

To see it in action against the current date, try running:

echo '<p>' . date('Y-m-d', strtotime('+1 day')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+2 weeks')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+3 months')) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+4 years')) . '</p>';

Of course, if you want to use a different base for its calculations, you would use the function like so:

echo '<p>' . date('Y-m-d', strtotime('+1 day', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+2 weeks', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+3 months', strtotime('2000-12-31'))) . '</p>';
echo '<p>' . date('Y-m-d', strtotime('+4 years', strtotime('2000-12-31'))) . '</p>';

Nifty.

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

PHP: Strtotime and Handling Different Date Formats Programming 27 OCT 2010

green php elephants - elephpantsStrtotime is a powerful date manipulating ally of any PHP developer, but unfortunately it doesn’t really respond to locale settings all that well, meaning that should you not be an American, in other words your dates don’t look like the silly MM/DD/YYYY format, it can return some rather strange and unexpected results!

Funnily enough though, there is in actual fact a pretty simple fix to this – and it all lies with the simple joining character you use to specify your date!

If like me you prefer the more logical European layout of DD-MM-YYYY, then make sure to use a dash (-) as your joining character. The usual forward slash (/) signifies American MM/DD/YYYY format while a humble period (or fullstop if you like) (.) indicates ISO YYYY.MM.DD.

And in action?

echo date("jS F, Y", strtotime("11.12.10")); 
// outputs 10th December, 2011 
echo date("jS F, Y", strtotime("11/12/10")); 
// outputs 12th November, 2010 
echo date("jS F, Y", strtotime("11-12-10")); 
// outputs 11th December, 2010  

Who would have guessed?

Still, damn useful now that you know! :)