网络编程
位置:首页>> 网络编程>> 数据库>> SQL中from_unixtime函数的使用方法实例

SQL中from_unixtime函数的使用方法实例

作者:小白修炼晋级中  发布时间:2024-01-14 12:45:01 

标签:sql,from,unixtime,函数

1.from_unixtime的语法及用法

(1)语法:from_unixtime(timestamp ,date_format)

即from_unixtime(时间戳 ,日期格式

参数说明

timestamp :时间戳,可为一串数字,也可为字段。

date_format:时间格式,不填默认为%Y-%m-%d %H:%i:%s的格式。

(2)用法:将时间戳转为指定日期格式。

(3)常见的日期格式

日期格式说明
%Y年,4位数字,如1999
%y年,2位数字,如00
%M月,英文月份,如January
%b月,缩写的月份名字,如Jan
%m月,数字(01……12)
%c月,数字(1……12)
%W星期,名字,如Sunday
%a星期,缩写的名字,如Sun
%D天,有英文前缀的天日期,如1st
%d天,月份中的天数,数字(01……31)
%e天,月份中的天数,数字(1……31)
%H小时,数字(00……23)
%k小时,数字(0……23)
%h小时,数字(01……12)
%l小时,数字(1……12)
%r时间,12 小时(hh:mm:ss [AP]M)
%T时间,24 小时(hh:mm:ss)
%S秒(00~59)
%s秒(00~59)

2.实例

例:现有一个产品信息表product,timestamp储存产品入库时间戳,产品名为name。获取入库时间为2020-02-01之后的每个产品信息及入库时间。

select ID,name,from_unixtime((timestamp + 8*3600),"%Y%-m-%d") as date
from product
where from_unixtime((timestamp + 8*3600),"%Y-%m-%d")>='2020-02-01'



select ID,name,from_unixtime((timestamp + 8*3600),"%Y-%m-%d %H:%i:%s") as date
from product
where from_unixtime((timestamp + 8*3600),"%Y-%m-%d")>='2020-02-01'



select ID,name,from_unixtime((timestamp + 8*3600),"yyyyMMdd") as date
from product
where from_unixtime((timestamp + 8*3600),"yyyy-MM-dd")>='2020-02-01'

因为想要获取北京时间的日期,存在时区问题,时间戳为GMT(格林尼治标准时间)需要加上8小时的时差转为北京时间。可根据实际情况转时差。

参考文章:mysql 时间戳格式化函数from_unixtime使用说明

时间戳的时区问题可参考: https://www.jb51.net/article/261129.htm

来源:https://blog.csdn.net/weixin_50853979/article/details/124873585

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com