mysql日期处理函数实例解析

发布时间:2022-04-18 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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年

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的mysql日期处理函数实例解析全部内容,希望文章能够帮你解决mysql日期处理函数实例解析所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。