首先創建一張實驗用的一張表
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() 函數
獲取當前時間
year() , month(),dayofmonth()
上面三個函數是分別從一個日期或者時間中提取出年 ,月 ,日
比如 想得到生日為2月份的學生
select * from t_student where month(birthday) = 2;
monthname() 函數
輸出個月份的英文單詞
select monthname(birthday) from t_student;
timestampdiff() 函數
比較兩個日期間的差值
例:學生的年齡
select timestampdiff(year,birthday ,now()) as age from t_student;
timestampdiff 函數的第一個參數為 計算結果的單位: 有year(年) month(月),day(日) 等等。
to_days()
將日期轉換成天數
計算兩個時間的天數,同timestampdiff(day,arg1,arg2) 是一個道理。
查詢生日小於當前日期60以內的學生
select * from t_student where (to_days(now()) - to_days(birthday)) < 60;
date_add 和 date_sub
根據一個日期 ,計算出另一個日期, 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年