phpdateadditiondurationseconds

PHP: add seconds to a date


I have $adate; which contains:

Tue Jan 4 07:59:59 2011

I want to add to this date the following:

$duration=674165; // in seconds

Once the seconds are added I need the result back into date format.

I don't know what I'm doing, but I am getting odd results.

Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.


Solution

  • If you are using php 5.3+ you can use a new way to do it.

    $date = new DateTime();
    echo $date->getTimestamp(). "<br>";
    $date->add(new DateInterval('PT674165S')); // adds 674165 secs
    echo $date->getTimestamp();
    

    The constructor syntax is explained in the constructor documentation as follows:

    The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.