1. current_date():获取当前格式化日期
select current_date() as today;
2. current_timestamp():获取当前格式化时间
select current_timestamp() as today;
3. unix_timestamp():获取当前unix时间戳
select unix_timestamp() as today;
4. from_unixtime():把unix时间戳转化为格式化时间
select from_unixtime(1653363939) as today;
注:第二个参数为时间格式,默认是’yyyy-MM-dd HH:mm:ss’
select from_unixtime(unix_timestamp(),'yyyy-MM-dd') as today;
5. to_date(): 当前格式化时间(含时分秒)转化为年月日
注:to_date() 默认转化格式为’yyyy-MM-dd’
select to_date('2022-05-23 23:00:01') as today;
6. date_format(): 对日期进行格式化
select date_format('2022-05-23 23:00:01','yyyy-MM-dd') as today;
select date_format('2022-05-23','yyyy-MM') as month;
select date_format('2022-05-23','yyyy') as year;
7. year/quarter/month/day/hour/minute/second: 年/季度/月/日/时/分/秒
select year('2022-05-01') as year;
select quarter('2022-05-23') as quarter;
select month('2022-05-01') as month;
select day('2022-05-23') as day;
select hour('2022-05-23 02:00:01') as hour;
select minute('2022-05-23 23:00:01') as minute;
select second('2022-05-23 23:00:01') as second;
8. date_add(): 取格式化时间的前/后n天
select date_add('2022-05-23',1) as tomorrow;
select date_add('2022-05-23',-7) as lastweek;
9. date_sub(): 取格式化时间的前/后n天
select date_sub('2022-05-23',1) as yeasterday;
select date_sub('2022-05-23',-1) as nextday;
10. add_months(): 当前时间的前/后n个月
select add_months('2022-05-23',1) as nextmonth;
select add_months('2022-05-23',-1) as lastmonth;
11. weekofyear(): 日期转周(当前的日期是一年中的第几周)
select weekofyear('2022-01-01') as 01week;
select weekofyear('2022-01-08') as 08week;
12. dayofyear(): 日期转天(当前的日期是一年中的第几天)
13. datediff(): 获取两个时间的天数差值
select datediff('2022-01-08 00:00:01', '2022-02-08 00:02:00') as diff;
select datediff('2022-03-08', '2022-02-08') as difftwo;
14. last_day(): 获取指定时间的当月的最后一天
select last_day('2022-02-05') as day;
15. next_day(): 获取指定时间的下一个星期几
注:next_day()第?个参数?持?写、?写、缩写(su/sun/sunday)
select next_day('2022-05-24','su') as nextsunday;
select next_day('2022-05-24','MON') as nextmonday;
16. trunc(): 获取当月第一天/获取当年的第一天
select trunc('2022-05-22','YY') as year;
select trunc('2022-05-22','MM') as month;
17. 常用时间
I.本周第一天&上周第一天
select date_sub(next_day('2022-05-23','monday'),7) as monday;
select date_sub(next_day('2022-05-25','monday'),14) as lastmonday;
II.本月第一天&本月最后一天&上月第一天
select trunc('2022-05-31', 'MM') as month;
select last_day('2022-02-05') as day;
select trunc(add_months('2022-05-31',-1), 'MM') as lastmonth;
|