Search code examples
phpdatetimeicalendardateintervalvcalendar

in PHP 5.4 How do I add 2 hours to a UTC date variable (and return UTC formatted for ical)


I have a date variable that I need to simply add 2 hours to. It needs to return UTC date formatted like: 20150921T172345Z .

None of the date manipulation examples I've seen are exactly what I need and I'm having a hard time converting what I've seen to my case.

Here's what I have now that isn't working:

//This yields exactly what I need for start date:
$rightNowUTC = gmdate("Ymd\THis\Z"); 

//But trying to add 2 hours gives an error. So what is wrong with syntax?
//  Start by creating end date variable that i will add the time to.
$endDateForWelcome = gmdate("Ymd\THis\Z");

//  Set duration (per examples I've seen)
$Duration = new DateInterval('PT2H'); // 2 hour

//  Then add duration to the date.
$endDateForWelcome->add( $Duration );

I get the next error:

PHP Fatal error: Call to a member function add() on a non-object.

This date will be written into an .ics file as an event end date (publishing a calendar file). So returning UTC is required. I've seen some code using

date(DATE_ICAL, strtotime($meeting->ends))

But I don't know how to adapt that to my needs.

Thanks in advance!


Solution

  • Try this:

    $rightNowUTC = gmdate("Ymd\THis\Z");  //time right now
    $endDateForWelcome = gmdate("Ymd\THis\Z", strtotime('+ 2 hours')); 
    

    $endDateForWelcome is a string so you have to parse it with strtotime()

    http://php.net/manual/en/function.strtotime.php

    echo "Time Right Now: ". $rightNowUTC ."</br>";
    echo "Time After Adding:".  $endDateForWelcome;