anees ma kader
anees ma kader

Reputation: 85

Incorrect time showing after converting to date format - PHP

Below is the time string I have,

'2019-12-30T15:42:33.891+11:00'

I tried to convert this to date format using below php code.

date('Y-m-d H:i:s',strtotime('2019-12-30T15:42:33.891+11:00')); 

And i am getting 2019-12-30 10:12:33 as the output. It seems date getting correctly but time not.

How to display the time also correctly? Thanks in advance!

Upvotes: 0

Views: 784

Answers (2)

jspit
jspit

Reputation: 7683

Your time string '2019-12-30T15:42:33.891+11:00' contains time zone information of +11:00. With date() the date and time are converted into the local time zone of your server. For example, I get "2019-12-30 05:42:33" (Timezone Europe/Berlin).

You can set a different time zone with date_default_timezone_set() or use DateTime to output the time for a location with the time zone "+11:00".

echo date_create('2019-12-30T15:42:33.891+11:00')->format('Y-m-d H:i:s');
//2019-12-30 15:42:33

strtotime () returns an integer timestamp. The Iformation of the Timezone +11:00 are lost in the process, but are processed when the time stamp is determined. The DateTime object always has a time zone.

echo '<pre>';
var_dump(date_create('2019-12-30T15:42:33.891+11:00'));

Output:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2019-12-30 15:42:33.891000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+11:00"
}

Note (Update):

When creating a DateTime object, the optional parameter for the time zone is only taken into account if the time string does not contain a time zone!

var_dump(new DateTime('2019-12-30T15:42:33.891 +11:00', new DateTimeZone('UTC')));

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2019-12-30 15:42:33.891000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+11:00"
}

//without +11:00
var_dump(new DateTime('2019-12-30T15:42:33.891', new DateTimeZone('UTC')));

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2019-12-30 15:42:33.891000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

Upvotes: 1

Meysam Zarei
Meysam Zarei

Reputation: 439

This date and time format relates to the "Zulu time" (UTC). UTC is refereed as Universal Time Coordinated. It is also known as “Z time” or “Zulu Time”.

You should change your timezone by some command like below code:

$date = new DateTime('2019-12-30T15:42:33.891+11:00', new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:s');

Or, for having more tools you can use the Carbon library.

Upvotes: 2

Related Questions