当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL常用时间函数详解(推荐)

MySQL常用时间函数详解(推荐)

2017年12月12日  | 移动技术网IT编程  | 我要评论

荞麦米,转身说爱你 白乐丝,叩壳网

2.6 date_sub/date_add

date_sub(date,interval expr type)

date 参数是合法的日期表达式。expr 参数是您希望添加的时间间隔。

select id from my_table where create_time >= date_sub(now(), interval 3 hour) and create_time < now();

type 值

•microsecond
•second
•minute
•hour
•day
•week
•month
•quarter
•year
•second_microsecond
•minute_microsecond
•minute_second
•hour_microsecond
•hour_second
•hour_minute
•day_microsecond
•day_second
•day_minute
•day_hour
•year_month

2.7 时间加减

当我们在给now()+-一个时间的时候,其实应该这样理解的:

+1/+01:加1秒钟
+101/+0101:加1分钟1秒钟
+10101/+010101:加1小时1分钟1秒钟
+1010101/+01010101:加1天1时1分钟1秒钟
+101010101/+0101010101:加1月1天1时1分钟1秒钟
+1101010101/+010101010101:加1年1月1天1时1分钟1秒钟,这里要注意下,年这个部分可以是4位(高位没有的话会补零):00010101010101

2.8 date_diff/time_diff

datediff(date1,date2)

datediff() 函数返回两个日期之间的天数(只比天),date1 和 date2 参数是合法的datetime/date表达式。

select datediff('2016-03-29','2016-03-29');

select datediff('2016-03-29 00:00:00','2016-03-29 23:59:59');

timediff(date1,date2)

timediff()函数返回两个日期之间的时分秒数(hh:mm:ss),date1 和 date2 参数是datetime/time表达式。

select timediff('2016-03-30 00:00:00','2016-03-28 11:11:11');

select timediff('00:00:00','11:11:11');

2.9 date_format

date_format(date,format)
date_format() 函数用于以不同的格式显示日期/时间数据。

select date_format(insert_time,'%y-%m-%d %h:%i:%s') as insert_time from user;

select date_format(insert_time,'%y-%m-%d') as day, count(id) as count from user group by day;

格式 描述
%a 缩写星期名
%b 缩写月名
%c 月,数值
%d 带有英文前缀的月中的天
%d 月的天,数值(00-31)
%e 月的天,数值(0-31)
%f 微秒
%h 小时 (00-23)
%h 小时 (01-12)
%i 小时 (01-12)
%i 分钟,数值(00-59)
%j 年的天 (001-366)
%k 小时 (0-23)
%l 小时 (1-12)
%m 月名
%m 月,数值(00-12)
%p am 或 pm
%r 时间,12-小时(hh:mm:ss am 或 pm)
%s 秒(00-59)
%s 秒(00-59)
%t 时间, 24-小时 (hh:mm:ss)
%u 周 (00-53) 星期日是一周的第一天
%u 周 (00-53) 星期一是一周的第一天
%v 周 (01-53) 星期日是一周的第一天,与 %x 使用
%v 周 (01-53) 星期一是一周的第一天,与 %x 使用
%w 星期名
%w 周的天 (0=星期日, 6=星期六)
%x 年,其中的星期日是周的第一天,4 位,与 %v 使用
%x 年,其中的星期一是周的第一天,4 位,与 %v 使用
%y 年,4 位
%y 年,2 位

以上就是小编为大家带来的mysql常用时间函数详解(推荐)全部内容了,希望大家多多支持移动技术网~

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网