Quick tip: Adding and substracting dates in PHP

More simple than it may seems. It will take care of adjusting months and days automatically:

Working with days:

// My date Y-m-d
$mydate = "2012-05-06";
//Adding five days
$newdate = date(“Y-m-d”, strtotime($mydate. " +5 days”));
// Substracting five days
$newdate = date(“Y-m-d”, strtotime($mydate. " -5 days”));

Working with weeks:

// My date Y-m-d
$mydate = "2012-05-06";
//Adding two weeks
$newdate = date(“Y-m-d”, strtotime($mydate. " +2 weeks”));
// Substracting one week
$newdate = date(“Y-m-d”, strtotime($mydate. " -1 week”));

Working with months

// My date Y-m-d
$mydate = "2012-05-06";
//Adding six months
$newdate = date(“Y-m-d”, strtotime($mydate. " +6 months”));
// Substracting three months
$newdate = date(“Y-m-d”, strtotime($mydate. " -3 months”));

Working with years

// My date Y-m-d
$mydate = "2012-05-06";
//Adding ten years
$newdate = date(“Y-m-d”, strtotime($mydate. " +10 years”));
// Substracting two years
$newdate = date(“Y-m-d”, strtotime($mydate. " -2 years”));

Be aware of the Unix Millenium Bug

Leave a Reply

Your email address will not be published. Required fields are marked *

*

8,043 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>