文章目录
时间戳位数
当时间戳有10 位时,可以转换到秒级。
13位的到毫秒。
注意转换!
天数
current_date 不是参数,只能取到当时真实的那天,所以如果要调度之前的日期,不可以用current_date,要把${date}转换成 ‘yyyy-MM-dd’ 的格式
${date}与current_date的转换
正确写法
unix_timestamp中必须是字符串,或者date形式
Current_date = from_unixtime(unix_timestamp(’${date}’,‘yyyymmdd’),‘yyyy-mm-dd’)
- 本月第一天(current_date)
select date_sub(current_date,dayofmonth(current_date)-1)
2019-04-01
select from_unixtime(unix_timestamp(date_sub(current_date,dayofmonth(current_date)-1),‘yyyy-MM-dd’),‘yyyyMMdd’)
20190401
select date_format(current_date,‘yyyy-MM-01’)
2019-05-01
错误写法
select from_unixtime(${date},'yyyy-MM-dd')
-- 1970-08-23
select from_unixtime(unix_timestamp(${date},'yyyymmdd'),'yyyy-mm-dd')
-- 重点! 要加‘’变成字符串
select from_unixtime(unix_timestamp(date_format(current_date,'yyyy-MM-01'),'yyyy-MM-dd'),'yyyyMMdd')
20190501
-
本月第一天(${date})
select from_unixtime(unix_timestamp(date_format(from_unixtime(unix_timestamp(‘20190228’,‘yyyymmdd’),‘yyyy-mm-dd’),‘yyyy-MM-01’),‘yyyy-MM-dd’),‘yyyyMMdd’) -
本月第2天
select date_sub(current_date,dayofmonth(current_date)-2)
2019-04-02 -
本月最后一天
last_day(string date),返回这个月的最后一天的日期
select last_day(current_date)
2019-04-30
select from_unixtime(unix_timestamp(last_day(current_date),‘yyyy-MM-dd’),‘yyyyMMdd’)
20190430 -
上个月
select add_months(current_date, -1);
2019-04-29 -
下个月
select add_months(current_date, 1);
2019-06-29 -
上月第一天
select add_months(date_sub(current_date,dayofmonth(current_date)-1), -1);
2019-04-01
select from_unixtime(unix_timestamp(add_months(date_sub(current_date,dayofmonth(current_date)-1), -1),‘yyyy-MM-dd’),‘yyyyMMdd’)
20190401 -
上月最后一天

本文详细介绍了Hive中处理时间的函数,包括时间戳转换、日期计算、日期格式化等。通过示例展示了如何正确使用current_date、date_sub、last_day、next_day等函数,并强调了在不同场景下的注意事项,如转换日期格式时需注意的错误和正确做法。
最低0.47元/天 解锁文章
382

被折叠的 条评论
为什么被折叠?



