Best method for PHP Timezones

浪尽此生 提交于 2019-12-24 10:49:42

问题


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'); }
?>

回答1:


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.



来源:https://stackoverflow.com/questions/1986453/best-method-for-php-timezones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!