MySQL日期时间转换函数

4 篇文章 0 订阅

比较常用日期函数有:

  • date_format();
  • time_format();
  • str_to_date();
  • to_days();
  • from_days();
  • time_to_sec();
  • sec_to_time();

日期/时间转换为字符串函数

date_format(date,format)

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d');

在这里插入图片描述

time_format(time,format)

SELECT time_format(NOW(), '%h:%i:%s');

在这里插入图片描述

字符串转换为日期函数:

str_to_date(str, format)

select str_to_date('08.09.2021 08:09:30', '%m.%d.%Y %h:%i:%s');

在这里插入图片描述

日期、天数转换函数:

to_days(date)

select to_days('2021-09-08') -- 738406
select to_days('0000-00-00'); -- NULL

在这里插入图片描述
from_days(days)

select FROM_DAYS(738406); -- 2021-09-08

在这里插入图片描述

时间、秒转换函数:

time_to_sec(time)

select time_to_sec('08:09:30'); -- 29370

在这里插入图片描述
sec_to_time(seconds)

select sec_to_time(29370); -- '08:09:30'

在这里插入图片描述

拼凑日期、时间函数:

makdedate(year,dayofyear)

select makedate(2021,31); -- '2021-01-31'
select makedate(2021,32); -- '2021-02-01'

在这里插入图片描述
maketime(hour,minute,second)

select maketime(12,15,30); -- '12:15:30'

在这里插入图片描述

Unix 时间戳、日期转换函数:

时间转时间戳

  • unix_timestamp()
  • unix_timestamp(date)
SELECT UNIX_TIMESTAMP(NOW());  

在这里插入图片描述
时间戳转时间

  • from_unixtime(unix_timestamp)
  • from_unixtime(unix_timestamp,format)
SELECT FROM_UNIXTIME(1777773871);

在这里插入图片描述

根据format字符串格式化date值:

%S, %s 两位数字形式的秒( 00,01, …, 59)
%I, %i 两位数字形式的分( 00,01, …, 59)
%H 两位数字形式的小时,24 小时(00,01, …, 23)
%h 两位数字形式的小时,12 小时(01,02, …, 12)
%k 数字形式的小时,24 小时(0,1, …, 23)
%l 数字形式的小时,12 小时(1, 2, …, 12)
%T 24 小时的时间形式(hh:mm:ss)
%r 12 小时的时间形式(hh:mm:ss AM 或hh:mm:ss PM)
%p AM或PM
%W 一周中每一天的名称(Sunday, Monday, …, Saturday)
%a 一周中每一天名称的缩写(Sun, Mon, …, Sat)
%d 两位数字表示月中的天数(00, 01,…, 31)
%e 数字形式表示月中的天数(1, 2, …, 31)
%D 英文后缀表示月中的天数(1st, 2nd, 3rd,…)
%w 以数字形式表示周中的天数( 0 = Sunday, 1=Monday, …, 6=Saturday)
%j 以三位数字表示年中的天数( 001, 002, …, 366)
%U 周(0, 1, 52),其中Sunday 为周中的第一天
%u 周(0, 1, 52),其中Monday 为周中的第一天
%M 月名(January, February, …, December)
%b 缩写的月名( January, February,…, December)
%m 两位数字表示的月份(01, 02, …, 12)
%c 数字表示的月份(1, 2, …, 12)
%Y 四位数字表示的年份
%y 两位数字表示的年份
%% 直接值“%”

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值