当前位置: 代码网 > it编程>数据库>Mysql > MySQL中DATE_FORMAT时间函数的使用小结

MySQL中DATE_FORMAT时间函数的使用小结

2025年08月06日 Mysql 我要评论
前言mysql可以使用date_format获取日期字段中的年月date_format时间函数1、 建立一个数据表set names utf8mb4;set foreign_key_checks =

前言

mysql可以使用date_format获取日期字段中的年月

date_format时间函数

1、 建立一个数据表

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for userloginlog
-- ----------------------------
drop table if exists `userloginlog`;
create table `userloginlog`  (
  `id` bigint(20) not null auto_increment,
  `userid` bigint(20) null default null,
  `isdelete` int(11) null default 0,
  `createtime` timestamp not null default current_timestamp,
  `updatetime` timestamp not null default current_timestamp
  primary key (`id`) using btree,
  index `idx_userid_appid`(`userid` asc, `appid` asc) using btree
) engine = innodb auto_increment = 407701224 character set = utf8mb4 collate = utf8mb4_general_ci row_format = dynamic;

set foreign_key_checks = 1;

可以操作createtime

select count(*) from userloginlog u where date_format(u.createtime,'%y') = '2024'

取出createtime中等于2024的年数据

2、 格式化时间

select date_format(u.createtime,'%y-%m') as month from userloginlog u

3、 统计月份数据

 select date_format(u.createtime,'%m') as month, count(*) from userloginlog u where date_format(u.createtime,'%y') = '2024'

group by month

4、 精确到天

select date_format(u.createtime,'%y-%m-%d')  from userloginlog u

格式描述
%a缩写星期名
%b缩写月名
%c月,数值
%d带有英文前缀的月中的天
%d月的天,数值(00-31)
%e月的天,数值(0-31)
%f微秒
%h小时 (00-23)
%h小时 (01-12)
%i小时 (01-12)
%i分钟,数值(00-59)
%j年的天 (001-366)
%k小时 (0-23)
%l小时 (1-12)
%m月名
%m月,数值(00-12)
%pam 或 pm
%r时间,12-小时(hh:mm:ss am 或 pm)
%s秒(00-59)
%s秒(00-59)
%t时间, 24-小时 (hh:mm:ss)
%u周 (00-53) 星期日是一周的第一天
%u周 (00-53) 星期一是一周的第一天
%v周 (01-53) 星期日是一周的第一天,与 %x 使用
%v周 (01-53) 星期一是一周的第一天,与 %x 使用
%w星期名
%w周的天 (0=星期日, 6=星期六)
%x年,其中的星期日是周的第一天,4 位,与 %v 使用
%x年,其中的星期一是周的第一天,4 位,与 %v 使用
%y年,4 位
%y年,2 位

总结

date_format() 函数用于以不同的格式显示日期/时间数据。

到此这篇关于mysql中date_format时间函数的使用小结的文章就介绍到这了,更多相关mysql date_format内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com