简体   繁体   English

在用户时区显示MySQL日期时间

[英]Display MySQL datetime in users timezone

MySQL datetimes created using now() are stored as UTC. 使用now()创建的MySQL日期时间存储为UTC。

Client side timezone is detected using JavaScript and returned as "Europe/London" . 使用JavaScript检测到客户端时区,并以"Europe/London"返回。

What is the best way to select the datetime from MySQL and display the created time in the users local time? 从MySQL选择日期时间并在用户本地时间显示创建的时间的最佳方法是什么?

PHP and Node are both used with MySQL. PHP和Node都与MySQL一起使用。

您可以使用MySQL CONVERT_TZ函数

SELECT CONVERT_TZ(NOW(), 'UTC', 'Europe/London')

I don't know how you logic is made, but I'm using this in PHP: 我不知道您的逻辑是如何产生的,但是我在PHP中使用它:

function utc_to_timezone($format, $date, $to_timezone)
{
    $date = new DateTime($date);
    $date->setTimezone(new DateTimeZone($to_timezone));

    return $date->format($format);
}

Example: 例:

echo utc_to_timezone('Y-m-d H:i:s', '2014-07-04 15:34:23', 'Europe/London');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM