Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP时区的最佳方法_Php_Javascript_Mysql_Time_Timezone - Fatal编程技术网

PHP时区的最佳方法

PHP时区的最佳方法,php,javascript,mysql,time,timezone,Php,Javascript,Mysql,Time,Timezone,问题1) 假设一个用户在我的应用程序中将时区设置保存为“America/New_York”,我会在需要的页面上使用它吗 使用时区偏移和夏令时显示正确的时间 <?php $time_zone = 'America/New_York'; date_default_timezone_set($time_zone); echo date('D,F j, Y, h:i:s A'); ?> 或者我应该使用类似的方法吗 当我查询数据时,我使用以下PHP脚本 <?PHP while($r

问题1)
假设一个用户在我的应用程序中将时区设置保存为“America/New_York”,我会在需要的页面上使用它吗 使用时区偏移和夏令时显示正确的时间

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

或者我应该使用类似的方法吗 当我查询数据时,我使用以下PHP脚本

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

我更喜欢根据用户对输出的偏好明确设置日期格式,而不是为整个执行脚本设置默认时区。这使得在保存数据或计算运行时间等操作中,使用UTC(默认情况下)中的日期变得更容易

您可以轻松编写考虑用户时区的日期格式化函数/方法。我通常加载用户时区一次,然后在每次后续的日期格式化调用中访问缓存的时区。这种快速方法可以防止我无意中使用或保存错误时区格式的数据