Adeel Aman
Adeel Aman

Reputation: 13

PHP parsing date with timezone from a string

I want to parse the date with the timezone from a string in the format "2021-12-10T18:49:00-05:00". I tried to parse using "date('Y-m-d h:i:s', strtotime($myDate))". But it is returning date of next day. Any help is much appreciated.

Upvotes: 0

Views: 837

Answers (4)

Álvaro González
Álvaro González

Reputation: 146460

The parsing bit of your code is done by strtotime() and it works just fine. The problem is in your debugging code, which translates the parsed date to a different time zone. Please compare:

$date = strtotime('2021-12-10T18:49:00-05:00');

var_dump(date_default_timezone_get(), date('r', $date));

date_default_timezone_set('Asia/Tokyo');
var_dump(date('r', $date));

date_default_timezone_set('America/Los_Angeles');
var_dump(date('r', $date));
string(16) "Europe/Amsterdam"
string(31) "Sat, 11 Dec 2021 00:49:00 +0100"
string(31) "Sat, 11 Dec 2021 08:49:00 +0900"
string(31) "Fri, 10 Dec 2021 15:49:00 -0800"

The result of strtotime() is a Unix timestamp, which is a fixed moment in time and isn't linked to any specific time zone. If you don't want to lose the time zone information you can use DateTime objects:

$date = new DateTime('2021-12-10T18:49:00-05:00');
var_dump($date);
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2021-12-10 18:49:00.000000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "-05:00"
}

This is something that only really matters if you application can actually handle different time zones.

Upvotes: 1

jspit
jspit

Reputation: 7703

The DateTime object can work well with time zones. The simple solution is therefore:

$strDate = "2021-12-10T18:49:00-05:00";
$dateTime = new DateTime($strDate);
var_dump($dateTime);
/*
object(DateTime)#2 (3) {
  ["date"]=>
  string(26) "2021-12-10 18:49:00.000000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "-05:00"
}
*/

The setTimeZone method can now be used to convert the date for any desired time zone.

$dateTime->setTimeZone(new DateTimeZone('UTC'));
echo $dateTime->format('Y-m-d H:i:s');
//2021-12-10 23:49:00 

I get the local time with

$tz = date_default_timezone_get();
$dateTime->setTimeZone(new DateTimeZone($tz));
echo $dateTime->format('Y-m-d H:i:s');

The result depends on the local time zone. For "Europe/Berlin" I get the result

2021-12-11 00:49:00

I get the same result (2021-12-11 00:49:00) with date and strtotime.

Upvotes: 1

ebnibrahem
ebnibrahem

Reputation: 109

short answer:

echo date('c'); //output 2021-12-10T17:28:24+03:00

to convert given date format use:

echo date('c', strtotime('2021-12-10')); //output 2021-12-10T00:00:00+03:00

Upvotes: 0

Angel Deykov
Angel Deykov

Reputation: 1227

Use DateTimeInterface::ATOM to format your date:

date(DateTimeInterface::ATOM, strtotime('now'));

This outputs 2021-12-10T14:23:37+00:00

Upvotes: 0

Related Questions