What is best practice for timezone handling in MySQL?

大憨熊 提交于 2020-01-12 08:01:08

问题


This has been asked before but not the answer I am looking for. I am storing all my dates in MYSQL in UTC/GMT. When I extract data fora user that references time is it better to use the CONVERT_TZ construct...

SELECT CONVERT_TZ(mytime,'UTC',usertimezone) as mytime FROM table

or is it better to temporarily set the session zone in Mysql and then do normal queries?

SET time_zone = usertimezone;

And if I use the second, do I just do that once for each user session or if I am not using a persistent open, do I need to set it before each query?


回答1:


If your data is stored in TIMESTAMP type columns, then you should SET time_zone and MySQL will automatically convert to/from UTC on retrieval/insertion—you don't need to do anything more. This is the recommended approach.




回答2:


  • Use TIMESTAMP if you want MySQL to do the conversion based on the time_zone setting of the current session.

  • Use DATETIME if you are returning UTC to your application for it to handle the conversion there. (This would be my preference.)

  • Don't try to mix these up. DATETIME will not do anything with the time_zone setting, and TIMESTAMP cannot be assumed to be UTC when it is returned to your application unless you are absolutely sure that time_zone is set to UTC.



来源:https://stackoverflow.com/questions/19254825/what-is-best-practice-for-timezone-handling-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!