简体   繁体   English

将MySQL UTC日期时间转换为UNIX时间戳

[英]Convert MySQL UTC datetime to UNIX timestamp

These both correctly return the current UNIX timestamp: 这些都正确返回当前的UNIX时间戳:

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

But I'm storing UTC_TIMESTAMPs in my database (not LOCALTIMESTAMPs). 但是我将UTC_TIMESTAMP存储在我的数据库中(而不是LOCALTIMESTAMP)。

How can I convert a UTC datetime to a UNIX timestamp using MySQL? 如何使用MySQL将UTC日期时间转换为UNIX时间戳?

Note that LOCALTIMESTAMP() is a synonym for NOW(). 请注意,LOCALTIMESTAMP()是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. 所以你真正要问的是如何获取当前时间并将其转换为GMT,然后转换为unix时间戳以存储在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. 顺便说一句,使用数据库的时间和日期列而不是unix时间戳总是好得多。 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 . UNIX_TIMESTAMP返回自UNIX时代以来基于UTC的秒数 It does not return a MySQL DateTime type . 它不返回MySQL DateTime类型 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. 如果您有一个实际的UTC DateTime实例,则可以将其直接放入数据库的DateTime列中,而不必使用UNIX_TIMESTAMP作为中介。 What type do you actually have that's in local time? 你当地有什么类型的?

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

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