Reputation: 10418
I'm building a project which is creating countdowns to various events, and I'm trying to keep it as timezone-agnostic as possible by just using UTC globally to avoid errors and issues, almost exactly similar to the one I'm getting now. The basic process is this:
Input Date/Time into database (stored similarly to ISO-8601):
2009-08-07 06:05:04
PHP representation:
Y-m-d H:i:s
Store in database with datetime
data type (which does not attempt to alter the datetimestamp from the server timezone to UTC - this would not be useful since I'm entering it in UTC anyway).
Retrieve from database, and manipulate into RFC-2822-like format (I do this because the date/time then gets plugged into a Javascript countdown, and Safari only accepts this particular format of date/time, annoyingly enough):
07 Aug 2009 06:05:04
PHP representation:
d M Y H:i:s
All of this is done, like I say, in UTC to avoid issues that appear when you start adding in timezones.
The issue I'm having appears to be occurring at or around step 3, where the date time gets reformatted. Here's my PHP function which does this:
function manipulateDateTime($inputDateTime, $utc_visible = true) {
$temp = DateTime::createFromFormat('Y-m-d H:i:s', $inputDateTime);
$outputDateTime = $temp->format('d M Y H:i:s');
if ($utc_visible === true) {
return $outputDateTime.' UTC';
} else {
return $outputDateTime;
}
}
Then I discovered that the DateTime
class had a constant aptly named DateTime::RFC2822
which Safari actually does accept... cool, I can remove my PHP format from line 3, replacing this:
$outputDateTime = $temp->format('d M Y H:i:s');
with this:
$outputDateTime = $temp->format(DateTime::RFC2822);
But when I do this, $outputDateTime
becomes equal to Fri, 03 Jan 2014 22:57:00 +0100
.
Where did that extra +0100 come from?
The I decide to print $temp
, my DateTime
object:
DateTime Object ( [date] => 2014-01-03 22:57:00 [timezone_type] => 3 [timezone] => Europe/Berlin )
Why am I seeing 'Europe/Berlin' and not 'UTC'?
A) I'm not in Europe/Berlin at all, I'm in New Zealand (UTC+13, if that matters), B) Why is not automatically formatted as UTC?
I'm having a hard time wrapping my head around whether this affects the countdowns that are built off this data, it doesn't seem to alter it, but it certainly is frustrating and unexpected. Anyone have any reasons for this?
Upvotes: 1
Views: 2907
Reputation: 2869
You either need to set date.timezone
in your php.ini
to UTC
or set it in your application using date_default_timezone_set()
.
That +0100 is coming from the RFC2822 format you chose. Documentation is here.
Upvotes: 1
Reputation: 449613
As to why this happens: your PHP install may have Europe/Berlin set as its default time zone.
Either way, createFromFormat
as a timezone
argument that you should be able to use:
...createFromFormat('Y-m-d H:i:s', $inputDateTime, new DateTimeZone("UTC"));
should do the trick.
Upvotes: 3