将 MySQL UTC 日期时间转换为 UNIX 时间戳
它们都正确返回当前 UNIX 时间戳:
SELECT UNIX_TIMESTAMP(LOCALTIMESTAMP()); #MySql
echo time(); //PHP
但我将 UTC_TIMESTAMP 存储在我的数据库中(而不是 LOCALTIMESTAMP)。
如何使用 MySQL 将 UTC 日期时间转换为 UNIX 时间戳?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,LOCALTIMESTAMP() 是 NOW() 的同义词。所以你真正要问的是如何获取当前时间并将其转换为 GMT,然后转换为 unix 时间戳以存储在数据库中。所以这会起作用:
顺便说一句,使用数据库的时间和日期列总是比使用 unix 时间戳要好得多。它使查询和显示结果变得更加容易。
更新:你确定你得到了你认为的那样吗? UNIX_TIMESTAMP 返回基于 UTC 的秒数UNIX 时代。它不返回 MySQL DateTime 类型。如果您有实际的 UTC DateTime 实例,则可以将其直接放入数据库的 DateTime 列中,而不必使用 UNIX_TIMESTAMP 作为中介。您实际上拥有当地时间的哪种类型?
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:
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?