Blackbam
Blackbam

Reputation: 19396

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?

Upvotes: 0

Views: 4289

Answers (2)

AymDev
AymDev

Reputation: 7609

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');

Upvotes: 4

Tom
Tom

Reputation: 3351

You can set the TimeZone of the DateTime object:

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

$date = date_create($timestamp);

$date->setTimezone(new DateTimeZone('Europe/Amsterdam'));

echo date_format($date, 'Y-m-d H:i:sP') . "\n";

Upvotes: 1

Related Questions