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

查看:63
本文介绍了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:

Catchable fatal error: Object of class DateTime could not be converted to string

第二,对于是否正确设置它以正确显示时区(在本例中为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天全站免登陆