Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force php strtotime to use UTC

I've seen a few questions about this but not a clear answer... strtotime() will use the default timezone set for PHP when converting the string to a unix timestamp.

However, I want to convert a string to unix timestamp in UTC. Since there is no parameter for doing so, how can this be done?

The string I'm trying to convert is: 2011-10-27T20:23:39, which is already in UTC. I want to represent that as a unix timestamp also in UTC.

Thank you

like image 947
Brian Avatar asked Oct 28 '11 02:10

Brian


2 Answers

I realize this question is very old, but I found another option that can be helpful. Instead of setting and then reverting php's time zone, you can specify the timezone as a part of the string you pass to strtotime like so:

echo date_default_timezone_get();
output: America/Chicago

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39'));
output: 2011-10-28 01:23:39

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39 America/Chicago'));
output: 2011-10-28 01:23:39

echo gmdate('Y-m-d H:i:s', strtotime('2011-10-27T20:23:39 UTC'));
output 2011-10-27 20:23:39

Note: I am on PHP 5.5.9, but this should work in any php version.

like image 67
Eric Seastrand Avatar answered Nov 12 '22 19:11

Eric Seastrand


Set the system default timezone before making the strtotime call:

date_default_timezone_set('UTC');
echo strtotime('2011-10-27T20:23:39')."\n";

// Proof:
print_r(getdate(strtotime('2011-10-27T20:23:39')));

// IMPORTANT: It's possible that you will want to
// restore the previous system timezone value here.
// It would need to have been saved with
// date_default_timezone_get().

See it in action.

like image 34
Jon Avatar answered Nov 12 '22 21:11

Jon