William J.
William J.

Reputation: 1584

Different behavior when printing DateTime depending on how the timezone was set

Why do I get different dates depending of how I set the timezone on the two code snippets below?

// Setting timezone using setTimezone' 
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00');
$date1->setTimezone(new DateTimeZone('UTC'));
$date1->add(new DateInterval('PT7776000S'));
echo $date1->format('c') . PHP_EOL;

prints 2018-07-03T10:00:00+00:00

// Setting timezone as a param to createFromFormat
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00', new DateTimeZone('UTC'));
$date2->add(new DateInterval('PT7776000S')); 
echo $date2->format('c') . PHP_EOL;

prints 2018-07-03T12:00:00+00:00

Upvotes: 1

Views: 53

Answers (2)

James
James

Reputation: 85

It looks like your second example properly adds 90 days (7776000 seconds) t0 the original date.

I think what is happening is that in the first example you are setting the time according to your current timezone (default) and then converting to UTC and then adding the seconds.

In the first example you are setting the timezone to UTC and setting the time, then adding the timeinterval.

Look at this older question's answer: Timezone conversion in php

Edit: Just saw @deceze already answered similarly. Still, take at the link to see other discussion/examples/etc.

Upvotes: 1

deceze
deceze

Reputation: 522382

When you instantiate DateTime without timezone information, the date is getting interpreted in whatever your default local timezone is; when you then set a new timezone, the date is getting converted to that timezone. I.e.:

$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00');

$date1 is 12:00:00 in, say, Europe/Berlin.

$date1->setTimezone(new DateTimeZone('UTC'));

$date1 is now 10:00:00 in UTC.

When you instantiate DateTime with timezone information, the date is getting interpreted as referring to a time in that timezone, and there's no conversion process afterwards. I.e.:

$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2018-04-04 12:00:00', new DateTimeZone('UTC'));

$date2 is 12:00:00 in UTC.

Upvotes: 2

Related Questions