mysql日期函数使用,统一日期字符串格式

您所在的位置:网站首页 mysql日期字符串截取 mysql日期函数使用,统一日期字符串格式

mysql日期函数使用,统一日期字符串格式

2024-07-15 13:09| 来源: 网络整理| 查看: 265

截取日期到分钟 left ('2021-11-03 10:00:20',16) //截取到前16位 获取当前时间前分钟的时间,截取日期到分钟 left (DATE_ADD(now(),INTERVAL -2 MINUTE),16) 将日期转为统一格式 在这里插入图片描述

如上图所示,addtime是varchar类型,保存日期,但日期表示有多种格式(时间戳、-、/、年),如何将所有日期修改为id为2的那种格式?

先说两个函数 1.日期转字符串函数,给定一个日期,返回指定格式的字符串,其实日期也是一种字符串,只不过需要符合日期格式

date_formate(date,format)//将日期按照指定格式字符串展示 select date_format(now(),'%Y-%m-%d %H:%i:%s'); select date_format(now(),'%Y/%m/%d %H:%i:%s'); select date_format(now(),'%Y年%m月%d日 %H:%i:%s');

2.将字符串转为日期

select str_to_date('2017年8月21日 05:03:22','%Y年%m月%d日 %H:%i:%s')

str_to_date(),第一个参数是要转为日期的字符串,可以是任意格式的字符串,第二个参数,是当前这个字符串年月日时分秒的占位符,用%Y,%m,%d %H,%s,%i填充。

有了这两个函数作为支撑以后,就可以进行统一转换了。接下来再介绍两个函数 select unix_timestamp(now())

unix_timestamp()传入一个日期,返回当前日期的时间戳。

select from_unixtime(1636259383)

from_unixtime(timestamp int,format varchar),而from_unixtime函数刚好可以将时间戳按照指定格式转换为时间,默认格式就是 xxxx-xx-xx .

所以时间格式统一思路就是将字符串日期先转为时间戳,再用from_unixtime函数转为统一格式日期。

将 / 格式的转为时间戳 update test_date_tb set addtime = unix_timestamp(str_to_date(addtime,'%Y/%m/%d %H:%i:%s')) where addtime like '%/%' 将 年 格式的转为时间戳 update test_date_tb set addtime = unix_timestamp(str_to_date(addtime,'%Y年%m月%d日 %H:%i:%s')) where addtime like '%年%'

此时表中的数据

在这里插入图片描述 最后再将时间戳转为日期字符串

update test_date_tb set addtime = from_unixtime(addtime) where addtime not like '%-%'

转换结果 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3