Mysql 日期,时间戳,字符串相互转换

一、函數介紹

1、date_format(date, format)

将date按照formatj进行格式化,
date 参数是合法的日期,
format 规定日期/时间的输出格式。

2、str_to_date(str, format)

将字符串转换为日期类型,输出结果为DATETIME类型的值,
str参数为目标字符串,
format 规定日期/时间的输出格式。
str中日期的格式要与format格式相同,否则结果为“NULL”。

3、unix_timestamp(date)

将date中的时间转换为时间戳,
date省略时,返回当前时间的时间戳。

4、from_unixtime(unix_timestamp, format)

将时间戳unix_timestamp转换为format中指定格式
unix_timestamp为目标时间戳
format 规定日期/时间的输出格式
format 为空时,默认为形同’%Y-%m-%d %h:%i:%s.%f’的格式。

二、实例

1、date_format(date, format)

select date_format(now(),'%Y-%m-%d')as a,#now()为获取当前日期和时间
date_format('2020-04-06','%Y-%m-%d')as b,
date_format('20200406','%Y-%m-%d') as c,
date_format('2020/04/06','%Y-%m-%d')as d,
date_format('2026','%Y-%m-%d')as e;#非日期格式

在这里插入图片描述

2、str_to_date(str, format)

select str_to_date('2020-04-06','%Y-%m-%d')as a,
str_to_date('2020-04-06 10:20:30','%Y-%m-%d')as b,
str_to_date('2020-4-6','%Y-%m-%d')as c,
str_to_date('2020/04/06','%Y/%m/%d')as d,
str_to_date('20200406','%Y%m%d')as e;

在这里插入图片描述

3、unix_timestamp()

select unix_timestamp()as a ,
unix_timestamp(now())as  b,
unix_timestamp('2020-04-08')as c,
unix_timestamp('2020/04/08')as d,
unix_timestamp('20200408')as e;

在这里插入图片描述

4、from_unixtime(unix_timestamp, format)

select from_unixtime('1586342435')as a ,
from_unixtime('1586342435','%Y-%m-%d')as  b,
from_unixtime('1586342435100','%Y-%m-%d')as c,#时间戳错误,时间戳格式需要到秒的格式
from_unixtime('1586342435','%Y-%m-%d %h:%i:%s.%f')as d;

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值