日期格式转换

1、日期函数

1)时间戳:unix_timestamp/from_unixtime

select unix_timestamp(); --查询当前时间的时间戳,返回 1486524284
select unix_timestamp('2017-02-08 11:15:50'); --查询指定时间的时间戳,返回 1486523750 (若转换失败返回0)
select unix_timestamp('20170208 11:00:00','yyyyMMdd HH:mm:ss'); --转换指定格式时间的时间戳
select from_unixtime(1486523750); --查询指定时间戳的时间,默认格式yyyy-MM-dd HH:mm:ss ,返回 2017-02-08 11:15:50
select from_unixtime(1486523750,'yyyyMMdd'); --查询指定时间戳的时间,转换成指定格式,返回 20170208

2)日期提取年月日时分秒+周:year/month/day/hour/minute/second/weekofyear

--查询指定日期的年月日时分秒和周,返回 2017、2、8、11、15、50、6
select year('2017-02-08 11:15:50'),month('2017-02-08 11:15:50'),day('2017-02-08 11:15:50'),hour('2017-02-08 11:15:50'),minute('2017-02-08 11:15:50'),second('2017-02-08 11:15:50'),weekofyear('2017-02-08 11:15:50'); 

3)日期时间转日期:to_date

select to_date('2017-02-08 11:15:50'); --查询指定日期时间中的日期。返回2017-02-08

to_date和from_unixtime区别:to_date不能转化整数型

4)日期比较

--日期比较,结束时间距离开始时间的天数。datediff(string enddate, string startdate)
select datediff('2017-02-02','2017-01-31');--返回 2

--日期增加和减少。date_sub (string startdate, int days)
select date_add('2017-01-31',2); --返回 2017-02-02
select date_sub('2017-02-02',2); --返回 2017-01-31

5)日期偏移

--自定义日期操作函数(返回带横线的日期):get_date
select get_date();--返回当前日期,返回 2017-02-09
select get_date(-2);--返回当前日期往前偏移2天的日期 ,返回 2017-02-07

--自定义日期操作函数(返回不带横线的日期):get_dt_date
select get_dt_date();--获取当前日期,返回 20170209
select get_dt_date(get_date(-2));--获取当前日期偏移,转为不带横杆的格式
select get_dt_date('2017-02-02',-2);--20170131

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值