Saturday, January 29, 2011

How to Add days, weeks, months, years to dates in PHP

How to Add days, weeks, months, years to dates in PHP

As you probably know php gives you a nice date() function that allows you to get a date and format it using a vast amount of unix date strings. But what if you want to add/subtract days, weeks and months to a date?

You can add any amount of time to a date in php using the strtotime function, this will allow manipulation of a date once it has been converted to a unix time string. See the example below:

$today = date("Y-m-d");// current date
$tomorrow = strtotime(date("Y-m-d", strtotime($today)) . " +1 day");
$output = date("Y-m-d", $tomorrow);

So the first line gets todays date, then the next command gets today and converts it to a time string with the modifier +1 day. This can be days, week, month or year depending on the requirements. Then we reformat the string as a date to output it. It’s really that simple.



No comments: