Apr
22
2009

Add Time to the Date Function in PHP

by   |  Posted in Tutorials  |  5 comments

I just needed to do this for a client’s site to set an expiration date for a user and I thought it might be something that other programmers might like to know how to do. If you need to take today’s date and add time to it it is pretty simple. There is a PHP function called date() and another called strtotime(). You need to use both to make this happen.

$date = date('Y-m-d');
$timestamp = strtotime(date("Y-m-d", strtotime($date)) . " + 1 month");
$expired = date('Y-m-d', $timestamp);

If you echoed out $date you would get today’s date formatted like “2009-04-21″.

If you echoed out $expired you would get today’s date plus 1 month, formatted like “2009-05-21″.

You can replace the “1 month” with “14 days” or “2 years” or whichever increment you need.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , ,

Short URL: http://bit.ly/cKFpZe

Discussion 5 Comments

  1. Marc on November 12, 2009 at 10:31 pm

    This just saved me a huge headache. Let me do something with Joomla that was driving me insane.

    Just wanted to say thanks!

  2. Ryan on November 16, 2009 at 1:56 am

    That’s a little more complicated than it needs to be.

    $date 	 = date('Y-m-d H:i:s');
    $newtime = strtotime($date . ' + 8 hours');
    $newtime = date('Y-m-d H:i:s', $newtime);
  3. ern on June 6, 2010 at 11:56 am

    thanks

  4. raven007 on February 28, 2011 at 7:10 am

    thanks ryan…

  5. manish patel on May 24, 2011 at 5:23 am

    this is very helpful for me