Convert MySQL UTC datetime to UNIX timestamp

瘦欲@ 提交于 2020-01-17 04:48:08

问题


These both correctly return the current UNIX timestamp:

SELECT UNIX_TIMESTAMP(LOCALTIMESTAMP()); #MySql
echo time(); //PHP

But I'm storing UTC_TIMESTAMPs in my database (not LOCALTIMESTAMPs).

How can I convert a UTC datetime to a UNIX timestamp using MySQL?


回答1:


Note that LOCALTIMESTAMP() is a synonym for NOW(). So what you're really asking is how to get the current time and convert it to GMT and then convert to a unix timestamp to store in the db. So this will work:

SELECT UNIX_TIMESTAMP(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'));

As an aside, it's always much better to use the time and date columns of a database rather than unix timestamps. It makes querying and displaying results much easier.

Update: Are you sure you are getting what you think you are? UNIX_TIMESTAMP returns a UTC based seconds since the UNIX epoch. It does not return a MySQL DateTime type. If you have an actual UTC DateTime instance, then you can put that directly into your DateTime column of your database and don't have to use UNIX_TIMESTAMP as an intermediary. What type do you actually have that's in local time?



来源:https://stackoverflow.com/questions/4548780/convert-mysql-utc-datetime-to-unix-timestamp

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