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

发布于 2024-10-09 23:00:50 字数 219 浏览 0 评论 0原文

它们都正确返回当前 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尐籹人 2024-10-16 23:00:50

请注意,LOCALTIMESTAMP() 是 NOW() 的同义词。所以你真正要问的是如何获取当前时间并将其转换为 GMT,然后转换为 unix 时间戳以存储在数据库中。所以这会起作用:

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

顺便说一句,使用数据库的时间和日期列总是比使用 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:

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文