HiveSQL实战积累_日期转换
1.日期格式转换
to_date()
to_date(时间戳/日期)的作用是返回时间戳中的日期部分,该函数的入参必须是timestamp类型或者date类型,返回值类型为string。
1 | 示例1:select to_date(cast('2010-12-08 10:03:01' as timestamp)) --timestamp时间戳作为参数 |
1 | 示例2:select to_date('2010-12-08 10:03:01') --date作为参数 |
date_format()
date_format(日期,格式)的作用是对给定的日期字符串进行格式化。
1 | 示例1:select date_format('2015-04-02 13:34:12','yyyy-MM-dd') |
2.时间戳转换
from_unixtime()
from_unixtime(时间戳,格式)的作用是将UNIX时间戳(从1070-01-01 00:00:00UTC到指定时间的秒数)转换为当前时区的指定格式时间字符串。
1 | 示例1:select from_unixtime(1505456567) --转换为默认日期格式yyyy-MM-dd HH:mm:ss |
1 | 示例2:select from_unixtime(1505456567,'yyyyMMdd') |
1 | 示例3:select from_unixtime(1505456567,'yyyy-MM-dd HH:mm:ss') |
1 | 示例4:select from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss') --unix_timestamp()获取系统当前时间 |
unix_timestamp()
unix_timestamp(日期,日期格式)的作用是将“yyyy-MM-dd HH:mm:ss“格式的日期转换为UNIX时间戳,如果是其它格式的时间字符串则需要加入日期格式。该函数的入参类型为date,返回值类型为bigint,共十位,单位为秒,若转换失败则返回0。
1 | 示例1:select unix_timestamp() --获取当前时区的UNIX时间戳 |
1 | 示例2:select unix_timestamp('2017-09-15 14:23:00') |
1 | 示例3:select unix_timestamp('2017-09-15 14:23:00','yyyy-MM-dd HH:mm:ss') |
1 | 示例4:select unix_timestamp('20170915 14:23:00','yyyyMMdd HH:mm:ss') |
3.日期计算
date_sub()
date_sub(startdate,intdays)用于对参数1日期减少参数2天数,参数2intdays可以是负数。
date_add()
date_add(startdate, intdays)用于对参数1日期增加参数2天数,参数2intdays可以是负数。
datediff()
datediff(enddate,startdate)用于计算两个日期之间相差的天数,前一个参数减去后一个参数。
add_months()
add_months(date,intmonths)用于对参数1日期增加参数2月份,参数2intmonths可以是负数。
1 | 示例1:select add_months('2019-01-21',-1) |
4.获取日期
year()|month()|day()|hour()|minute()|second()|quarter()
year(date)|month(date)|day(date)|hour(date)|minute(date)|second(date)|quarter(date)用于返回date类型或timestamp类型入参的年|月|日|时|分|秒|季度,返回值类型为int。
weekofyear()
weekofyear(date)用于获取指定日期在一年中属于第几周,入参类型为date,返回值类型为int。
current_date
current_date用于返回当前日期。
1 | 示例1:select current_date |
current_timestamp
current_timestamp用于返回当前时间。
1 | 示例1:select current_timestamp |
last_day()
last_day(date)用于返回入参时间的当月最后一天日期
1 | 示例1:select last_day('2019-06-21') |
next_day()
next_day(date,周几)用于返回入参时间的下周几的具体日期
1 | 示例1:select next_day('2021-05-28','MO') --2021-05-28往后的第一个周一 |
1 | 示例2:select next_day('2020-01-01','Fri') --2020-01-01往后的第一个周五 |