1. 程式人生 > 資料庫 >mysql日期處理函式例項解析

mysql日期處理函式例項解析

這篇文章主要介紹了mysql日期處理函式例項解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

首先建立一張實驗用的一張表

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年

 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。