First, create an experiment with a table
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());
Type where date is the date accurately record type mysql
now () function
to get the current time
year (), month (), dayofmonth ()
above three functions are extracted respectively in from a date or time, month, day,
for example, wanted birthday in February, students
select * from t_student where month (birthday ) = 2;
monthname () function
Output a month of English words
select monthname (birthday) from t_student;
timestampdiff () function of
the difference between the two dates comparative
example: age of the students
select timestampdiff (year, birthday, now ()) as age from t_student;
The first argument timestampdiff function as a unit calculation results: there year (Year) month (February), day (day), and so on.
TO_DAYS ()
converts a date several day long
in days two times, with timestampdiff (day, arg1, arg2) is a reason.
Query birthday less than the current date less than 60 students
select * from t_student where (to_days ( now ()) - to_days (birthday)) <60;
DATE_ADD and date_sub
according to one date to another date is calculated, plus date_sub DATE_ADD is obtained by subtracting
select date_add ( '1970-1-1', interval 10 year); # 1970 plus 10 years in
select date_sub ( '1970-1-1', interval 10 year); # 1970 of minus 10 years