PHP时区的最佳方法 [英] Best method for PHP Timezones

查看:67
本文介绍了PHP时区的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题1)
假设用户在我的应用程序中将时区设置另存为"America/New_York",我是否可以在需要 显示正确的时间并加上时区偏移和夏令时

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

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

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

推荐答案

我更喜欢根据用户对输出的偏好来显式格式化日期,而不是为整个执行脚本设置默认时区.这使得在默认情况下使用UTC中的日期进行操作更加容易,例如用于保存数据或计算经过时间的操作.

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.

这篇关于PHP时区的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆