Mysql日期数据类型
- Mysql保存日期格式使用 yyyy-MM-dd HH:mm:ss 的ISO 8601标准
timestamp时间戳格式
timestamp格式的使用期限是: 1970-1-1 到 2038年; timestamp格式的字段, 可以在行记录更新时, 自动更新时间.
表设计如下:
执行 update t_user set birthday='1980-2-12 17:09:14' where user_id=1
, 可操作 birthday字段
日期格式化输出
date_format(‘日期类字段’, ‘格式化字段’)
常用占位符:
%Y 年
%m 月
%d day of month %j day of year
%T 时(24小时制) %r 时(12小时, AM PM)
%i 分
%s 秒
举例:
# 这里查看所有记录(自行插入)
select * from t_user
# 格式化日期输出
select user_id, user_name, DATE_FORMAT(birthday,'%Y年%m月%d日') AS birthday
from t_user
时间处理函数
从日期中取值:
select user_id, user_name, year(birthday),month(birthday),day(birthday),
hour(birthday),minute(birthday),second(birthday)
from t_user
计算时间差
# 以日为单位计算(向下取整)
select timestampdiff(day,birthday,now())
from t_user;
# 以年为单位计算(向下取整)
select TIMESTAMPDIFF(year,birthday,now())
from t_user;
比较时间:
直接用不等号比较
select * from t_user
where birthday BETWEEN '1993-3-2' and '1995-3-3'
select * from t_user
where birthday >= '1993-3-2'
and birthday <= '1995-3-3'
两个查询得到一样的结果