Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily convert dates from UTC via PHP?

Tags:

timezone

php

I am storing dates in a MySQL database in datetime fields in UTC. I'm using PHP, and I've called date_timezone_set('UTC') so that all calls to date() (without timestamp) return the date in UTC.

I then have it so a given web site can select its timezone. Now I want dates to display in the site's timezone. So, if I have a date stored as '2009-04-01 15:36:13', it should display for a user in the PDT timezone (-7 hours) as '2009-04-01 08:36:13'.

What is the easiest (least code) method for doing this via PHP? So far all I've thought of is

date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));

Is there a shorter way?

like image 260
Chad Johnson Avatar asked Jun 04 '09 20:06

Chad Johnson


People also ask

What timezone is UTC for PHP?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts. See PHP's list of supported timezones to find the names of all possible timezones you can use for the date.

How can we convert the time zones using PHP?

It's really simple to convert a DateTime from one time zone to another in PHP. Just create a DateTime object using date & time to be converted as the first parameter and the original time zone as the second parameter. Then change the time zone to the desired one using the setTimezone method. That's all!


1 Answers

Why not use the built in DateTime/TimeZone functionality?

<?php

$mysqlDate = '2009-04-01 15:36:13';

$dateTime = new DateTime ($mysqlDate);
$dateTime->setTimezone(new DateTimeZone('America/Los_Angeles'));

?>

DateTime Class: http://us3.php.net/manual/en/class.datetime.php DateTimeZone Class: http://us3.php.net/manual/en/class.datetimezone.php

PHP's supported Timezones: http://php.net/manual/en/timezones.php

like image 80
Jordan S. Jones Avatar answered Oct 21 '22 08:10

Jordan S. Jones