免费学习推荐:mysql视频教程
目录
第一部分:时间差函数 timestampdiff、datediff、timediff一、时间差函数:timestampdiff二、时间差函数:datediff三、时间差函数:timediff四、其他日期函数其他日期函数第二部分 日期、时间戳、字符串互相转换其他第一部分:时间差函数 timestampdiff、datediff、timediff
一、时间差函数:timestampdiff
语法:timestampdiff(interval, datetime1,datetime2)
结果:返回(时间2-时间1)的时间差,结果单位由 interval 参数给出。
interval
frac_second 毫秒(低版本不支持,用second,再除于1000)
second 秒
minute 分钟
hour 小时
day 天
week 周
month 月
quarter 季度
year 年
注意:mysql 5.6之后才支持毫秒的记录和计算,如果是之前的版本,最好是在数据库除datetime类型之外的字段,再建立用于存储毫秒的int字段,然后自己进行转换计算。# 所有格式
select timestampdiff(frac_second,'2012-10-01','2013-01-13'); # 暂不支持select timestampdiff(second,'2012-10-01','2013-01-13'); # 8985600select timestampdiff(minute,'2012-10-01','2013-01-13'); # 149760select timestampdiff(hour,'2012-10-01','2013-01-13'); # 2496select timestampdiff(day,'2012-10-01','2013-01-13'); # 104select timestampdiff(week,'2012-10-01','2013-01-13'); # 14select timestampdiff(month,'2012-10-01','2013-01-13'); # 3select timestampdiff(quarter,'2012-10-01','2013-01-13'); # 1select timestampdiff(year,'2012-10-01','2013-01-13'); # 0
二、时间差函数:datediff
语法:select datediff(日期1, 日期2)
结果:日期1 - 日期2 的天数的差
slect datediff('2013-01-13','2012-10-01'); # 104
三、时间差函数:timediff
语法:timediff(time1,time2)
结果:返回 time1-time2 的差值
select timediff('2018-05-21 14:51:43','2018-05-19 12:54:43');#49:57:00
注意:该方法两个参数必须为日期格式
四、其他日期函数
now()函数返回的是当前时间的年月日时分秒curdate()函数返回的是年月日信息curtime()函数返回的是当前时间的时分秒信息对一个包含年月日时分秒日期格式化成年月日日期,可以使用date(time)函数其他日期函数
select now(); # 2018-05-21 14:41:00select curdate(); # 2018-05-21select curtime(); # 14:41:38select date(now()); # 2018-05-21select sysdate(); # 2018-05-21 14:47:11select current_time(); # 14:51:30select current_timestamp; # 2018-05-21 14:51:37select current_timestamp(); # 2018-05-21 14:51:43
注意:now()与sysdate()类似,只不过now()在执行开始时就获取,而sysdate()可以在函数执行时动态获取。
第二部分 日期、时间戳、字符串互相转换
#时间日期转字符串 相当与oracle中的to_char函数select date_format(now(), '%y-%m-%d'); #结果:2017-02-27#时间转时间戳select unix_timestamp(now()); #结果:1488160428#字符串转时间select str_to_date('2017-02-27', '%y-%m-%d %h'); #结果:2017-02-27 00:00:00select str_to_date('2017-10-16 15:30:28','%y-%m-%d %h:%i:%s'); #结果 2017-10-16 15:30:28#注意 年是大写‘y’,小时也必须是大写‘h’ (如果其他为大写,则得到结果为null)#字符串转时间戳select unix_timestamp('2017-02-27'); #结果:1488124800#时间戳转时间select from_unixtime(1488160428); #结果:2017-02-27 09:53:48#时间戳转字符串select from_unixtime(1488160428,'%y-%m-%d %t'); #结果:2017-02-27 09:53:48 select date_format(curdate(),'%y-%m-%d %h:%i:%s'); -- 获取当天零点select curdate(); --获取当前日期select last_day(curdate()); --获取当月最后一天。select date_add(curdate(),interval -day(curdate())+1 day); --获取本月第一天select date_add(curdate()-day(curdate())+1,interval 1 month); -- 获取下个月的第一天select datediff(date_add(curdate()-day(curdate())+1,interval 1 month ),date_add(curdate(),interval -day(curdate())+1 day)) from dual; --获取当前月的天数
其他
select day('2021-2-17') -- 当前月的第几天(17)select month('2021-2-17') -- 当前为几月(2)
更多相关免费学习推荐:mysql教程(视频)
以上就是聊聊mysql 中常用的日期相关函数的详细内容。