您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)如何在mysql中使用日期處理函數(shù),小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
首先創(chuàng)建一張實(shí)驗(yàn)用的一張表
drop table if exists t_student; create table t_student( id int primary key auto_increment, name varchar(20) not null comment '姓名', birthday date comment '生日' )Engine=InnoDB default charset utf8; insert into t_student values(null,'tom','1992-02-03'); insert into t_student values(null,'jerry','1993-02-06'); insert into t_student values(null,'hank','1993-03-05'); insert into t_student values(null,'xiaoming',now());
其中date 類型 是記錄mysql 精確日期的類型
now() 函數(shù)
獲取當(dāng)前時(shí)間
year() , month(),dayofmonth()
上面三個(gè)函數(shù)是分別從一個(gè)日期或者時(shí)間中提取出年 ,月 ,日
比如 想得到生日為2月份的學(xué)生
select * from t_student where month(birthday) = 2;
monthname() 函數(shù)
輸出個(gè)月份的英文單詞
select monthname(birthday) from t_student;
timestampdiff() 函數(shù)
比較兩個(gè)日期間的差值
例:學(xué)生的年齡
select timestampdiff(year,birthday ,now()) as age from t_student;
timestampdiff 函數(shù)的第一個(gè)參數(shù)為 計(jì)算結(jié)果的單位: 有year(年) month(月),day(日) 等等。
to_days()
將日期轉(zhuǎn)換成天數(shù)
計(jì)算兩個(gè)時(shí)間的天數(shù),同timestampdiff(day,arg1,arg2) 是一個(gè)道理。
查詢生日小于當(dāng)前日期60以內(nèi)的學(xué)生
select * from t_student where (to_days(now()) - to_days(birthday)) < 60;
date_add 和 date_sub
根據(jù)一個(gè)日期 ,計(jì)算出另一個(gè)日期, date_add 是加上 date_sub 是減去
select date_add('1970-1-1', interval 10 year); # 1970 年 加上10年
select date_sub('1970-1-1', interval 10 year); #1970年減去10年
以上就是如何在mysql中使用日期處理函數(shù),小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。