我想转换一个像这样的字符串:
'10/15/2008 10:06:32 PM'
转换为Sql Server中的DATETIME值。
在甲骨文,我会这样说:
TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
这个问题意味着我必须将字符串解析为一种标准格式,然后使用其中一种代码进行转换。对于这样一个平凡的行动来说,这似乎很荒谬。有没有更简单的方法?
我想转换一个像这样的字符串:
'10/15/2008 10:06:32 PM'
转换为Sql Server中的DATETIME值。
在甲骨文,我会这样说:
TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
这个问题意味着我必须将字符串解析为一种标准格式,然后使用其中一种代码进行转换。对于这样一个平凡的行动来说,这似乎很荒谬。有没有更简单的方法?
当前回答
用这个:
SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm
转换代码请参考官方文档中的表格。
其他回答
这段代码解决了我的问题:
convert(date,YOUR_DATE,104)
如果你使用时间戳,你可以你下面的代码:
convert(datetime,YOUR_DATE,104)
If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.
通过您的查询处理器运行它。它格式化日期和/或时间,其中一个应该会给你你要找的东西。适应并不难:
Declare @d datetime
select @d = getdate()
select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,12),12,'yymmdd'
union all
select @d,convert(varchar,@d,112),112,'yyyymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'
对于这个问题,我使用的最好的解决方案是在Sql Server 2005中有一个使用DateTime的CLR函数。Parse或ParseExact函数返回指定格式的DateTime值。
简短的回答:
SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]
其他日期格式可以在SQL Server Helper > SQL Server日期格式中找到