在sql server中,可查询日期和时间,常见类型有
- date: 日期格式,格式为'yyyy-mm-dd' 即年月日,yeer-month-day
- time:时间类型,格式为 'hh:mi:ss'。 即时分秒,hour-minute-seconds
- datetime:日期和时间类型,格式为 'yyyy-mm-dd hh:mi:ss'。即date和time结合,中间有空格,末尾新增毫秒(millisecond)。
1.纯数字表示format
--getdate()是打印当前时间的函数,包含日期时间,时分秒毫秒 select getdate() --2023-10-15 13:44:15.420 -- (1) 纯时间 --134004 select replace(convert(varchar(8), getdate(), 108), ':', ''); --(2)纯日期 --20231015 select replace(convert(varchar(8), getdate(), 112), ':', ''); --(3)纯日期时间 --20231015134004 select convert(varchar(10), getdate(), 112) + replace(convert(varchar(8), getdate(), 108), ':', '')
2. convert的使用
convert格式:convert(data_type(length),expression,style)
data_type(length):规定显示的长度,固可以将显示的长度缩短,也可以得到需要的结果。
select convert(varchar(50), getdate(), 109); --oct 15 2023 2:04:54:123pm select convert(varchar(11), getdate(), 109); --oct 15 2023
expression:getdate() 或者自行输入需要处理的时间值。
style: 类型
id | style | format | region |
1 | 101 | mm/dd/yy | usa |
2 | 102 | yy.mm.dd | ansi |
3 | 103 | dd/mm/yy | british/french |
4 | 104 | dd.mm.yy | german |
5 | 105 | dd-mm-yy | italian |
6 | 106 | dd mon yy | |
7 | 107 | mon dd, yy | |
8 | 108 | hh:mm:ss | |
- | 9 or 109 | mon dd yyyy hh:mi:ss:mmmam (or pm) | default+millisec |
10 | 110 | mm-dd-yy | usa |
11 | 111 | yy/mm/dd | japan |
12 | 112 | yymmdd | iso |
- | 13 or 113 | dd mon yyyy hh:mi:ss:mmm (24h) | |
14 | 114 | hh:mi:ss:mmm (24h) | |
- | 20 or 120 | yyyy-mm-dd hh:mi:ss (24h) | |
- | 21 or 121 | yyyy-mm-dd hh:mi:ss.mmm (24h) | |
- | 126 | yyyy-mm-ddthh:mi:ss.mmm (no spaces) | iso8601 |
- | 130 | dd mon yyyy hh:mi:ss:mmmam | hijiri |
- | 131 | dd/mm/yy hh:mi:ss:mmmam | hijiri |
示例:
--2023-10-15 select convert(date, getdate()) as date, --13:47:52.5130000 select convert(time, getdate()) as time; --13:47:52 select convert(varchar(10), getdate(), 108);
3.日期与字符串之间的转换
-- 将日期转换为字符串 select convert(varchar, getdate(), 120) as convertedtime; -- 将字符串转换为日期 select convert(date, '2022-01-01', 120) as converteddate;
验证:
-- 将日期转换为字符串 select convert(varchar, getdate(), 120) as convertedtime into #tt1 --select...into table,带#是生成一个临时表 go --go使得前面语句先执行完成,在执行后边语句 select * from #tt1; select sql_variant_property(convertedtime, 'basetype') as datatype from #tt1; drop table #tt1 --使用完临时表,删除掉,节约资源
-- 将字符串转换为日期 select convert(date, '2023-10-15', 120) as converteddate into #tt2; go select * from #tt2 select sql_variant_property(converteddate, 'basetype') as datatype from #tt2; drop table #tt2
到此这篇关于sql server日期时间格式转化的方式小结的文章就介绍到这了,更多相关sql server时间格式转化内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论