使用 MySQL 将 Unix 时间戳转换为人类可读的日期
是否有 MySQL 函数可用于将 Unix 时间戳转换为人类可读的日期?我有一个字段用于保存 Unix 时间,现在我想添加另一个字段用于人类可读的日期。
Is there a MySQL function which can be used to convert a Unix timestamp into a human readable date? I have one field where I save Unix times and now I want to add another field for human readable dates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用
FROM_UNIXTIME()
:另请参阅:MySQL 文档
FROM_UNIXTIME()
。Use
FROM_UNIXTIME()
:See also: MySQL documentation on
FROM_UNIXTIME()
.其他答案中缺少的并且不直接明显的是
from_unixtime
可以采用第二个参数来指定格式,如下所示:What's missing from the other answers (as of this writing) and not directly obvious is that
from_unixtime
can take a second parameter to specify the format like so:我认为您正在寻找的是
FROM_UNIXTIME()
I think what you're looking for is
FROM_UNIXTIME()
需要特定时区的 Unix 时间戳吗?
如果您可以快速访问 mysql cli,这里有一个简单的说明:
将
'MST'
替换为您想要的时区。我住在亚利桑那州Need a unix timestamp in a specific timezone?
Here's a one liner if you have quick access to the mysql cli:
Replace
'MST'
with your desired timezone. I live in Arizona ???? thus the conversion from UTC to MST.为什么要费心将字段保存为可读?只有我们
AS
编辑:抱歉,我们以毫秒而不是秒存储所有内容。修好了。
Why bother saving the field as readable? Just us
AS
EDIT: Sorry, we store everything in milliseconds not seconds. Fixed it.
您可以使用 DATE_FORMAT 函数。 这里是一个包含示例的页面,以及可用于选择不同日期组件的模式。
You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.
简单易行的方法:
select from_unixtime(column_name, '%Y-%m-%d') from table_name
Easy and simple way:
select from_unixtime(column_name, '%Y-%m-%d') from table_name
因为我发现这个问题没有意识到,mysql总是将时间存储在UTC的时间戳字段中,但会在本地时区显示(例如phpmyadmin),我想添加我的发现。
我有一个自动更新的last_modified字段,定义为:
用phpmyadmin查看它,看起来是本地时间,内部是UTC
在任何星座中,UNIX_TIMESTAMP和'as UTC'总是以UTC时间显示。
运行两次,第一次不设置 time_zone。
Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.
I have an automatically updated last_modified field, defined as:
Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC
In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.
Run this twice, first without setting the time_zone.
如果您想转换时间并以特定格式显示数据,您可以使用此字符串。
将
convert_tz
添加到 date_format 字符串。%m/%d/%y
为月/日/年
。您可以在这里找到所有特定格式 https://www.w3schools.com/sql/func_mysql_date_format。 ASP
If you would like to convert time AND display the data in a specific format you can use this string.
where you add
convert_tz
to a date_format string. the%m/%d/%y
beingmonth/day/year
.you can find all the specific formats here https://www.w3schools.com/sql/func_mysql_date_format.asp