PHP将UTC时间转换为本地时间 [英] PHP convert UTC time to local time

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

问题描述

像下面的格式一样,从服务器获取UTC时间时,我的要求是将UTC时间转换为本地时间。因此,用户可以根据时区在浏览器中看到用户友好的时间。请帮我解决这个问题。谢谢

Am getting a UTC time from my server like the following format, my requirement is to convert the UTC time to local time. So users can see a user friendly time on their browser based on their timezone. Please help me to solve this issue. Thank you

$utc = "2014-05-29T04:54:30.934Z"

我尝试了一些方法,但不适用于我的情况

I have tried some methods but not working in my case

首先

$time = strtotime($utc);
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;

第二

$time = strtotime($utc .' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;


推荐答案

您的代码无法正常工作的原因很可能是因为您的服务器处于UTC时间。因此,服务器的本地时间是UTC。

The reason your code isn't working is most likely because your server is in UTC time. So the local time of the server is UTC.

一种可能的解决方案是在服务器端进行以下操作,并将纪元整数传递给浏览器:

One potential solution is to do the following server side and pass the epoch integer to the browser:

$utc = "2014-05-29T04:54:30.934Z";
$time = strtotime($utc); //returns an integer epoch time: 1401339270

然后使用JavaScript将纪元整数转换为用户的本地时间时间(浏览器知道用户的时区)。

Then use JavaScript to convert the epoch integer to the user's local time (the browser knows the user's timezone).

您可以让浏览器发送您用户的时区。然后,您可以使用此信息来计算日期字符串服务器端而不是浏览器端。在此处查看更多信息: https://stackoverflow.com/a/5607444/276949

You can get the browser to send you the user's timezone. Then you can use this information to calculate the date string server side instead of browser side. See more here: https://stackoverflow.com/a/5607444/276949

这将为您提供用户的补偿(-7小时)。您可以在以下位置使用此信息来设置时区:将UTC偏移量转换为时区或日期

This will give you the user's offset (-7 hours). You can use this information to set the timezone by looking here: Convert UTC offset to timezone or date

这篇关于PHP将UTC时间转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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