Javascript – Best method for PHP Timezones

javascriptMySQLPHPtimetimezone

Question 1)
Assuming a user has a timezone setting saved as 'America/New_York' in my application, would I just use this on a page where I need to
show the correct time with timezone offset and daylight savings applied

<?php
$time_zone = 'America/New_York';
date_default_timezone_set($time_zone);
echo date('D,F j, Y, h:i:s A');
?>

OR should I use something more like this approach
When I query my data I use the following PHP script

<?PHP
while($row = mysql_fetch_array($registration)){ 

$dt_obj = new DateTime($row['message_sent_timestamp']." UTC");
$dt_obj->setTimezone(new DateTimeZone('America/New_York'));
echo $formatted_date_long=date_format($dt_obj, 'Y-m-d H:i:s'); }
?>

Best Answer

I prefer to explicitly format dates according to user preferences on output, rather than set a default timezone for the entire executing script. That makes it easier to work with dates in, say, UTC by default, for actions such as saving data or calculating elapsed times.

You can easily write a date formatting function/method that takes into account user timezone. I usually load the user timezone once, then on each subsequent date formatting call, access the cached timezone. This quick method prevents me from inadvertently using or saving data in the wrong timezone format.