一、基础时间函数
1)current_date()
作用:
得到当前的日期字符串
.
select current_date();
结果:2021-01-01
2)current_timestamp()
作用:
得到当前的时间字符串
.
select current_timestamp();
结果:2020-01-01 13:52:46.018
3) unix_timestamp()
作用:
得到当前的时间戳
.
select unix_timestamp();
结果:1577858367
4) 提取日期所在的年、月、日
year(someDate)
,month(someDate)
, day(someDate)
作用:
得到当前日期所在的年份,月份,日期
.
select year(‘2020-01-31’),year(‘2020-01-31 13:14:15’),month(‘2020-01-31’),month(‘2020-01-31 13:14:15’),day(‘2020-01-31’),day(‘2020-01-31 13:14:15’);
结果:2020,2020,1,1,31,31
5)date_format
函数(根据格式整理日期)
作用:
把一个字符串日期格式化为指定的格式
.
select date_format(‘2017-01-01’,‘yyyy-MM-dd HH:mm:ss’); --日期字符串必须满足yyyy-MM-dd格式
结果:2017-01-01 00:00:00
6)date_add
、date_sub
函数(加减日期)
作用:
把一个字符串日期格式加一天、减一天
.
select date_add(‘2019-01-01’,1); --字符串必须满足yyyy-MM-dd格式
结果:2019-01-02
.
select date_sub(‘2019-01-01’,1); --字符串必须满足yyyy-MM-dd格式
结果:2018-12-31
7)next_day
函数
作用:
得到一个字符串日期的下周几的具体日期
.
select next_date(‘2020-01-01’,‘Fri’); --得到2020-01-01往后的第一个周五
结果:2020-01-03
8)last_day
函数(求当月最后一天日期)
作用:
求当月的最后一天日期
.
select last_day(‘2020-01-01’);
结果:select last_day(‘2020-01-01’);
9)from_unixtime
(‘bigint时间戳’,‘pattern’)函数
作用:
把一个数字类型的时间戳,转换为指定格式的日期字符串
通常情况下,9、10是在一起用的,常用来把非yyyy-MM-dd的日期字符串转为标准的yyyy-MM-dd的日期字符串
select from_unixtime(1517725479,‘yyyy-MM-dd HH:dd:ss’);
结果:2018-02-04 14:04:39
.
select from_unixtime(1517725479,‘yyyyMMdd’);
20180204
10)unix_timestamp('日期字符串','pattern')
通常情况下,9、10是在一起用的,常用来把非yyyy-MM-dd的日期字符串转为标准的yyyy-MM-dd的日期字符串
.
作用:把指定格式的日期转成时间戳
.
select unix_timestamp(‘2020/01/01’,‘yyyy/MM/dd’);
结果:1577808000
11)date_format('日期字符串','pattern')
作用:日期格式化
案例:
-- 获取星期几(1,2,3,4,5,6,7),对应周一到周日
select date_format('2021-01-01', 'u');
7)add_months
函数
作用:
当前日期基础行,增加n个月
. 如当日为2020-06-03
select add_months(current_date, 3), add_months(current_date, -3);
结果:2020-09-03, 2020-03-03
二、综合案例
1、获取当周的周一
select date_sub(next_day(‘2021-06-26’,‘Mon’),7) as monday_1; --推荐
.
select date_sub(next_day(‘2021-06-26’,‘Tue’),8) as monday_2;
.
select date_sub(
‘2021-06-26’,
cast(date_format(‘2021-06-26’, ‘u’) as int) -1
) as monday_3;
2、获取指定日期为周几
注意:pmod函数返回值(0,1,2,3,4,5,6),对应(周日,周一,..,周六)
方法①:
select pmod(
datediff(date_sub('2021-01-01', 0), '1920-01-01') - 3,
7
) as day_of_week_1,
pmod(
datediff(date_sub('2021-01-03', 0), '1920-01-01') - 3,
7
) as day_of_week_1;
结果:5,0
方法②:
如果想让周一到周六对应数字1-7只需要将查询出来的数据进行判断就行了,如下:
IF(pmod(datediff(#date#, '1920-01-01') - 3, 7)='0', 7, pmod(datediff(#date#, '1920-01-01') - 3, 7));
方法③:
select
case when pmod(datediff(local_time,'2018-01-01') + 1,7) = 1 then 'Monday'
when pmod(datediff(local_time,'2018-01-01') + 1,7) = 2 then 'Tuesday'
when pmod(datediff(local_time,'2018-01-01') + 1,7) = 3 then 'Wednesday'
when pmod(datediff(local_time,'2018-01-01') + 1,7) = 4 then 'Thursday'
when pmod(datediff(local_time,'2018-01-01') + 1,7) = 5 then 'Friday'
when pmod(datediff(local_time,'2018-01-01') + 1,7) = 6 then 'Saturday'
else 'Weekend'
end time_interval;