user3760395
user3760395

Reputation: 3

Converting date from xml to readable format

I have a xml file, containing several dates, in this format: 2016-07-23T07:00:00.000Z. I'm using a php function to convert this in to a format for publishing on a website. This should actually result in something like Saturday, 24th of July (24th, not 23rd, because of the time offset. My function somehow ignores the T07:00:00.000Z part and thus returns Friday, 23rd of July. Can anybody help me out with the proper way to convert this date?

Thanks, Peter

Upvotes: 0

Views: 1896

Answers (2)

hakre
hakre

Reputation: 197682

The string in question

2016-07-23T07:00:00.000Z

is a W3C datetime format (W3C DTF) (Complete date plus hours, minutes, seconds and a decimal fraction of a second) which can be properly parsed incl. the fractions of a second with the date_create_from_format](http://php.net/date_create_from_format) function:

$originalDate = "2016-07-23T07:00:00.000Z";
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);

It does create a new DateTime which then can be formatted with the for PHP standard codes, e.g.

date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
    ->format('Y-m-d H:i:s'); # 2016-07-23 07:00:00

As that W3C format carries the timezone already and it is UTC, and you wrote you want a different one, you need to specify it:

date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
    ->setTimezone(new DateTimeZone('Asia/Tokyo'))
    ->format('Y-m-d H:i:s');

The reason why this is not visible (and controlable with the code given) in the previous answer is because date formats according to the default set timezone in PHP where as each DateTime has it's individual timezone.

An equivalent with correct parsing (incl. decimal fraction of a second) with the other answers then is:

$dateTime = date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);
date('Y-m-d H:i:s', $dateTime->getTimestamp());

Hope this explains it a bit better in case you need the complete date value and / or more control on the timezone.

For the format, see as well: In what format is this date string?

Upvotes: 1

Scarraban
Scarraban

Reputation: 106

$oldDateTime= "2016-07-23T07:00:00.000Z"; // Your datetime as string, add as variable or whatever.
$newDateTime= date("Y-m-d H:i:s", strtotime($originalDate));

Upvotes: 0

Related Questions