简体   繁体   中英

Display MySQL datetime in users timezone

MySQL datetimes created using now() are stored as UTC.

Client side timezone is detected using JavaScript and returned as "Europe/London" .

What is the best way to select the datetime from MySQL and display the created time in the users local time?

PHP and Node are both used with 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:

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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