获取当前的日期和时间
# 查看当前日期和时间
select now(); # 2022-09-24 09:29:05
# 下面这三个函数, 可以不加括号, 也可以加上括号
select current_date, current_time, current_timestamp ;
# 2022-09-24 09:34:00 2022-09-24 09:34:00
从时间中获取日期
select
date(current_timestamp) # 2022-09-24
, year(current_timestamp) # 2022
, month(current_timestamp) # 9
, day(current_timestamp()); # 24
日期的加减
select current_date(); # 2022-09-24
select date_add(current_date(), interval 1 day); # 2022-09-25
select date_add(current_date(), interval 1 month); # 2022-10-24
select date_sub(current_date(), interval 1 day); # 2022-09-23
select date_sub(current_date(), interval 1 year); # 2021-09-24
select date_sub(current_date(), interval -1 month); # 2022-10-24
日期差和时间差的计算
select datediff('2022-09-27', '2022-09-23'); # 4
select timediff('2022-09-27 11:20:10', '2022-09-27 10:10:00'); # 01:10:10
# 注意后面两个参数是前小后大, 和datediff不同
select timestampdiff(day, '2022-09-20', '2022-09-23') ; # 3
select timestampdiff(hour, '2022-09-20 10:20:30', '2022-09-20 12:30:30') ;
# 2
select timestampdiff(second, '2022-09-20 10:20:30', '2022-09-20 12:30:30') ;
# 7800
字符串和日期的互换
# 字符串-> 日期
select str_to_date('20220927', '%Y%m%d');
# 2022-09-27 第二个参数是对第一个参数的格式解释
select str_to_date('2022/9/27', '%Y/%m/%d'); # 2022-09-27
select str_to_date('2022年9月27日', '%Y年%m月%d日'); # 2022-09-27
# 日期-> 字符串
select date_format(current_timestamp(), '%Y%m%d'); # 20220924
select date_format(current_timestamp(), '%Y年%m月%d日'); # 2022年09月24日
时间戳和日期的互换
select unix_timestamp(); # 1663985175
# 日期或者时间字符串 -> 时间戳
select unix_timestamp('2022-09-20 10:20:30'); # 1663640430
select unix_timestamp('2022-09-20'); # 1663603200
# 时间戳 -> 日期
select from_unixtime(1663640430); # 2022-09-20 10:20:30