PHP/MySQL 时区说明 [英] PHP/MySQL Timezone Clarification

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

问题描述

我目前在思考将我的 MySQL 时间转换为特定时区的想法时遇到了一个问题,具体取决于用户的设置.

I'm currently having an issue wrapping my brain around the notion of converting my MySQL time to a specific timezone, depending on the user's settings.

我所有的 MySQL 时间都以 UTC 时间存储,格式如下:

All of my MySQL times are stored in UTC time, in the following format:

2009-11-08 17:06:40

查询时间后,我不太确定如何使用 PHP 将其转换为适当的时区.

Once I query the time, I'm not quite sure how to convert it to the appropriate timezone using PHP.

因此,在上面的示例中,我想显示:

Thus, in the example above, I'd like to display:

2009-11-08 09:06:40

这是我目前拥有的(可能需要修复):

Here's what I currently have (which probably needs to be fixed):

$sql = 'SELECT date FROM mytable';
    require("connection.php");
    $result = mysql_db_query($DBname,$sql,$link); 
    while($row = mysql_fetch_assoc($result)) { 

    $dt_obj = new DateTime($row['date']); 
    $dt_obj->setTimezone(new DateTimeZone('PST')); 
    echo $dt_obj;       
    echo "<br>";
     }

首先,我收到以下错误:

First off, I get the following error:

可捕获的致命错误:DateTime 类的对象无法转换为字符串

其次,我很困惑我是否正确设置它以在正确的时区显示时间(在本例中为 PST).

Secondly, I am confused as to whethere I'm setting it up properly to display the time in the correct timezone anyway (in this case, PST).

任何有关如何执行此操作的建议将不胜感激.谢谢!

Any suggestions on how to do this would be greatly appreciated. Thanks!

更新:

我接受了 GZipp 的建议,并将代码修改为:

I took GZipp's advice, and modified the code to look like:

$dt_obj->setTimezone(new DateTimeZone('America/Los_Angeles')); 
echo $dt_obj->format('Y-m-d H:i:s');

但是,我的时间(使用上面的示例)显示为:

However, it's displaying my time (using the example from above) as:

2009-11-08 15:06:40

有什么想法会导致这种情况吗?

Any ideas on what would be causing this?

推荐答案

我想这就是你所追求的;

I think this is what you're after;

$dt_obj = new DateTime($row['date']); 
$dt_obj->setTimezone(new DateTimeZone('America/Los_Angeles')); 
echo $dt_obj->format('Y-m-d H:i:s');

使用支持的时区列表.

更新已编辑问题:为确保 PHP 将数据库中的时间视为 UTC 时间,请执行以下操作:

Update to edited question: To ensure that PHP sees the time from the database as UTC time, do something like this:

$row['time'] = '2009-11-08 09:06:40';

$dt_obj = new DateTime($row['time'], new DateTimeZone('UTC')); 
echo 'UTC: ' . $dt_obj->format('Y-m-d H:i:s') . '<br />';  // UTC: 2009-11-08 09:06:40
$dt_obj->setTimezone(new DateTimeZone('America/Los_Angeles')); 
echo 'Los Angeles: ' . $dt_obj->format('Y-m-d H:i:s');  // Los Angeles: 2009-11-08 01:06:40

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

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