Calculate total seconds in PHP DateInterval

Calculate total seconds in PHP DateInterval

Asked on December 24, 2018 in PHP.
Add Comment


  • 3 Answer(s)

    The code for calculate total seconds in PHP DateInterval is here.

    Try to use timestamp instead of Dateinterval.

    $now = new DateTime('now');
    $diff = $date->getTimestamp() - $now->getTimestamp()
    
    Answered on December 24, 2018.
    Add Comment

    In DateInterval object one can get the total duration of seconds by using this function,

    The example code,

    /**
    * @param DateInterval $dateInterval
    * @return int seconds
    */
    function dateIntervalToSeconds($dateInterval)
    {
    $reference = new DateTimeImmutable;
    $endTime = $reference->add($dateInterval);
    return $endTime->getTimestamp() - $reference->getTimestamp();
    }
    
    Answered on December 24, 2018.
    Add Comment

    Try this code,

    $currentTime = time();
    $timeInPast = strtotime("2009-01-01 00:00:00");
     
    $differenceInSeconds = $currentTime - $timeInPast;
    

    The current time in seconds since the epoch time which is 1970-01-01T00:00:00 is gives by the time() function. strtotime does the samething, but based on a specific date or time , it may change.

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.