php中的时区转换 [英] Timezone conversion in php
问题描述
任何人都可以建议一个简单的方法来将日期和时间转换为PHP中的不同时区?
Can anyone suggest an easy method to convert date and time to different timezones in php?
推荐答案
可以使用datetime对象或其函数别名为:
You can use the datetime object or their function aliases for this:
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
有关评论的修改
但是我不能使用此方法,因为我需要在不同的时区显示日期,因为用户从不同的位置登录
but i cannt use this method because i need to show date in different time zones as the user login from different locations
这不是问题。当用户登录时,您可以确定他的时区,并将其设置为DateTime对象,如图所示。我在我的一个项目中使用类似的方法,它的作用就像一个魅力。
That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.
在数据库中我需要获取日期在任何一个时区,只有它可以正确处理
in the database i need to get the dates in any single timezone, then only it can be processed properly
您可以将时间作为一个时区或时间戳存储在一个时区。当您查询DateTime字段时,您可以将DateTime对象中的时间转换为此时区,或者 - 如果您的数据库支持它,则会使用所选时区查询。
You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.
这篇关于php中的时区转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!