温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在mysql中使用日期处理函数

发布时间:2021-05-14 16:12:02 来源:亿速云 阅读:137 作者:Leah 栏目: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() 函数

获取当前时间

如何在mysql中使用日期处理函数

year() , month(),dayofmonth()

上面三个函数是分别从一个日期或者时间中提取出年 ,月 ,日

比如 想得到生日为2月份的学生

select * from t_student where month(birthday) = 2;

如何在mysql中使用日期处理函数

monthname() 函数

输出个月份的英文单词

select monthname(birthday) from t_student;

如何在mysql中使用日期处理函数

timestampdiff() 函数

比较两个日期间的差值

例:学生的年龄

select timestampdiff(year,birthday ,now()) as age from t_student;

如何在mysql中使用日期处理函数

timestampdiff 函数的第一个参数为 计算结果的单位: 有year(年) month(月),day(日) 等等。

to_days()

将日期转换成天数

计算两个时间的天数,同timestampdiff(day,arg1,arg2) 是一个道理。

查询生日小于当前日期60以内的学生

select * from t_student where (to_days(now()) - to_days(birthday)) < 60;

如何在mysql中使用日期处理函数

date_add 和 date_sub

根据一个日期 ,计算出另一个日期, date_add 是加上 date_sub 是减去

select date_add('1970-1-1', interval 10 year); # 1970 年 加上10年

如何在mysql中使用日期处理函数

select date_sub('1970-1-1', interval 10 year); #1970年减去10年

 如何在mysql中使用日期处理函数

以上就是如何在mysql中使用日期处理函数,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI