Search code examples
phpdateunix-timestampiso8601gmt

How to convert ISO 8601 timestamp without timezone to ISO 8601 timestamp with timezone in PHP?


My timestamp is like this:

$timestamp = "2018-08-28T08:49:44+00:00";

Easy to convert this to a unix timestamp:

$unixtime = strtotime($timestamp);
echo $unixtime; // result: 1535446184

My desired result is to get the timestamp with timezone for my current timezone. It should be like this:

$timestamp_with_timezone = "2018-08-28T10:49:44+02:00";

However if I do:

echo date('c',$unixtime);

The result is again:

2018-08-28T08:49:44+00:00

What is the correct way to get the desired local time date in ISO 8601 format?


Solution

  • Using the DateTime class:

    // DateTime automatically parses this format, no need for DateTime::createFromFormat()
    $date = new DateTime("2018-08-28T08:49:44+00:00");
    
    // Set the timezone (mine here)
    $date->setTimezone(new DateTimeZone('Europe/Paris'));
    
    // Output: 2018-08-28T10:49:44+02:00
    echo $date->format('c');