日期的转换
1. 格式转换:date_format() ‘2022-04-15’ -> ‘20220415’
select date_format('2022-04-15', 'yyyyMMdd')
2. 时间戳和日期转换:from_unixtime, unix_timestamp
select unix_timestamp('2022-04-15')
select from_unixtime(1649980800, 'yyyyMMdd HH:mm:ss')
3. 标准时间:to_date()
注意,这里传入的时间是yyyy-MM-dd …这种格式
select to_date('2022-04-15 12:00:00');
如果想要把不同类型的时间变成标准时间,可以先转换为时间戳,再转换成日期
select from_unixtime(unix_timestamp('2022/04/15', 'yyyy/MM/dd'), 'yyyy-MM-dd');
4. 日期差
-
date_sub
select date_sub('2022-04-15', 3);
![在这里插入图片描述](https://img-blog.csdnimg.cn/bb1d49205a554047af2c2d75cbefc832.png)
-
date_add
select date_add('2022-04-15', 3);
-
datediff
select datediff('2022-04-15', '2022-04-13');
5. 周、月计算
-
weekofyear():一年的第几周
select weekofyear('2022-04-15');
- dayofweek():一周的第几天
-
next_day():该日期下周几的日期
select next_day('2022-04-15', 'Fri');
-
last_day():当月最后一天的日期
select last_day(current_date);
6. 当前日期和时间
-
current_date():获取当前日期
select current_date();
-
current_timestamp():获取当前时间
select current_timestamp();