MySQL 日期、时间的加减法,以及date_format函数

一、加减某个时间间隔:date_add()与 date_sub()函数

1. date_add() :加

select date_add('2019-12-12', interval 1 day) dayTime,
       date_add('2019-12-12', interval 1 month) monthTime,
       date_add('2019-12-12', interval 1 year) yearTime;

2. date_sub() :减

select date_sub('2019-12-12', interval 1 day) dayTime,
       date_sub('2019-12-12', interval 1 month) monthTime,
       date_sub('2019-12-12', interval 1 year) yearTime;

二、日期相减:datediff()与 timedifff()函数

1. datediff(date1,date2):两个日期相减,得到相减(date1减date2)之后的“天数”

select datediff('2019-12-12','2019-11-11') intervalDay;

2. timediff(time1,time2):两个时间相减,得到相减(time1减time2)之后的时间“差值”

select timediff('18:30:30','08:50:00') intervalTime;

三、日期格式化:date_format()函数

date_format(date, formate):用于以不同的格式显示日期/时间数据,date 参数是合法的日期,format 规定日期/时间的输出格式。

select date_format(NOW(), '%Y-%m-%d') time1,
       date_format(NOW(), '%b %d %Y %h:%i %p') time2,
       date_format(NOW(), '%m-%d-%Y') time3,
       date_format(NOW(), '%d %b %y') time4,
       date_format(NOW(), '%d %b %Y %T:%f') time5;

开发中通常会使用第一种format方式:'%Y-%m-%d'

更多精彩,请关注我的"今日头条号":Java云笔记
随时随地,让你拥有最新,最便捷的掌上云服务

发布了147 篇原创文章 · 获赞 169 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_44259720/article/details/103496184