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'
兩個查詢得到一樣的結果