mysql关于时间的一些函数

获取当前的日期和时间

# 查看当前日期和时间
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值