简体   繁体   English

在T-SQL中将日期时间转换为nvarchar(8)

[英]Conversion of datetime to nvarchar(8) in T-SQL

I'm trying to convert a datetime column to ISO format, as yyyymmdd . 我正在尝试将datetime列转换为yyyymmdd ISO格式。 For example, I would like to be able to convert '13 dec 2018' to '20181213'. 例如,我希望能够将'13 dec 2018'转换为'20181213'。

According to Microsoft's T-SQL Docs , I should be able to do this using 根据Microsoft的T-SQL文档 ,我应该能够使用

convert(nvarchar(8), '13 dec 2018', 112)

however this doesn't work - I get the result '13 dec 2', which looks to be nothing more than the original string cut down to 8 characters. 但是,这不起作用-我得到的结果是'13 dec 2',它看起来只不过是原始字符串,该字符串减少到8个字符。

I have also tried using 我也尝试使用

convert(datetime, '13 dec 2018', 112)

which gives me the result of 'Dec 13 2018 12:00AM' - again, nothing like what the function is supposed to produce. 这给了我'Dec 13 2018 12:00 AM'的结果-同样,没有什么应该产生的功能。

What I am doing wrong? 我做错了什么? I could solve the problem easily enough using datepart() and concatenated strings, but I'd rather use the more elegant approach if possible. 我可以使用datepart()和连接的字符串轻松地解决问题,但如果可能的话,我宁愿使用更优雅的方法。

Combine them: 合并它们:

convert(nvarchar(8), convert(datetime, '13 dec 2018'), 112)

I don't recommend using the format 112 for the first conversion, because it is misleading. 我不建议您为第一次转换使用格式112 ,因为它会引起误解。 SQL Server is very good at converting without a format. SQL Server非常擅长进行无格式转换。 If you do use one the appropriate one is 106 . 如果确实使用一种,则合适的是106

I figured it out - because I was entering the date as a string, and not converting it to a datetime value first, it was treating my date as if it were a string. 我知道了-因为我是将日期作为字符串输入,而不是先不将其转换为datetime值,所以它会将我的日期视为字符串。 When I handle it this way: 当我这样处理时:

convert(nvarchar(8), cast('13 dec 2018' as datetime), 112)

I get the expected result, '20181213'. 我得到了预期的结果'20181213'。

select convert(nvarchar(8), cast(GETDATE() as datetime), 112) as TodayDate 选择convert(nvarchar(8),cast(GETDATE()作为datetime),112)作为TodayDate

在此处输入图片说明

YYYYMMDD format can obtain by datetime to varchar format. YYYYMMDD格式可以按日期时间获取为varchar格式。

select convert(varchar(8),convert(datetime, '13 dec 2018'),112)

The above query provides the required result 上面的查询提供了所需的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM