Do you know how I can convert this to a strtotime, or a similar type of value to pass into the DateTime object?
The date I have:
Mon, 1
While @drrcknlsn is correct to assert there are multiple ways to convert a time string to a datatime, it's important to realize that these different ways don't deal with timezones in the same way.
DateTime('@' . $timestamp)
Consider the following code :
date_format(date_create('@'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
The strtotime
bit eliminates the time zone information, and the date_create
function assumes GMT (Europe/Brussels
).
As such, the output will be the following, no matter which server I run it on :
2011-12-12T13:17:52+00:00
date_create()->setTimestamp($timestamp)
Consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800')), 'c');
You might expect this to produce the same output. However, if I execute this code from a Belgian server, I get the following output :
2011-12-12T14:17:52+01:00
Unlike the date_create
function, the setTimestamp
method assumes the time zone of the server ('Europe/Brussels'
in my case) rather than GMT.
If you want to make sure your output matches the time zone of your input, it's best to set it explicitly.
Consider the following code :
date_format(date_create('@'. strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Now, also consider the following code :
date_format(date_create()->setTimestamp(strtotime('Mon, 12 Dec 2011 21:17:52 +0800'))->setTimezone(new DateTimeZone('Asia/Hong_Kong')), 'c')
Because we explicitly set the time zone of the output to match that of the input, both will create the same (correct) output :
2011-12-12T21:17:52+08:00