duanshang9426 2013-03-12 05:17
浏览 112
已采纳

如何正确存储和使用MySQL TIMESTAMP与不同的时区? [关闭]

I am creating an application that based on scheduling appointments, in an environment where a user can select their desired timezone.

After doing some research, I was convinced to use MYSQL's TIMESTAMP to store all dates. I thought that, when using TIMESTAMP, all dates would be converted and stored as UTC. Then, a TIMESTAMP column would convert to the timezone of MYSQL when pulling the date from the database.

Below is some example code of my current setup:

On each page, the timezones are set for PHP and MYSQL (Based on user selection. PST for this example):

date_default_timezone_set('US/Pacific');
SET time_zone = '-08:00'

When putting a time into MYSQL, I would just convert a timestamp to the proper format.

date("Y-m-d H:i:s", $unix_timestamp);

When pulling form the database, I would simply use MYSQL to convert to UNIX.

SELECT UNIX_TIMESTAMP(created_at) as created_at FROM `table` WHERE id=1

This was elegant, and seemed to work perfectly. MySQL was doing all the heavy lifting of timezone conversion for me, just by using TIMESTAMP. That is, Until a Daylight Savings Time happened. Now, anytime a non-UTC timezone is selected, the time is an hour off.

What am I doing, wrong? Please help!

  • 写回答

2条回答 默认 最新

  • doudan1123 2013-03-12 05:47
    关注

    If you use;

    date_default_timezone_set('US/Pacific');
    SET time_zone = '-08:00'
    

    ...MySQL's server time zone will be one hour off from Pacific time in the summers since PDT is GMT-07:00. Instead use for example;

    date_default_timezone_set('US/Pacific');
    SET time_zone = 'America/Los_Angeles';
    

    ...and MySQL's server time will support DST changes and you should get the correct time zone conversions.

    Since MySQL doesn't always contain all available time zones, if the time zone America/Los_Angeles is missing from your system, this page should help you install it.

    Since you're using dynamic time zones per user, you may need some kind of lookup table to translate between MySQL and PHP time zones, so you can set them both correct per user.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!