本文介绍了将 ISO 格式的日期转换为 DATETIME的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SQL Server Management Studio 编写 SQL 查询,并且有一些 ISO 日期格式的 NVARCHAR 类型值(例如:20130302T164800).我需要将它们转换为 DATETIME

I am writing a SQL query using SQL Server Management Studio and there are some NVARCHAR type values in ISO date format (example: 20130302T164800). I need to convert them to a DATETIME

我尝试了 Convert() 函数,但它导致异常:

I tried the Convert() function but it causes an exception:

将 nvarchar 数据类型转换为 datetime 数据类型导致值超出范围

有没有办法做到这一点?

Is there a way I can do this?

推荐答案

问题在于您的字符串不是可接受的 SQL Server 日期时间格式.SQL Server 识别 ISO8601 格式,即:

The problem is that your string is not an accepted SQL Server datetime format. SQL Server recognises the ISO8601 format, which is:

yyyy-mm-ddThh:mi:ss.mmm

您上面的日期是 2013-03-02T16:48:00.

请参阅日期和时间样式部分.

因此以下语句将失败:

declare @date nvarchar(max) = '20130302T164800'

select convertedDate = cast(@date as datetime)

如果您将字符串转换为 ISO8601 格式,该语句将起作用:

If you convert the string to the ISO8601 format, the statement will work:

declare @date nvarchar(max) = '2013-03-02T16:48:00'

select convertedDate = cast(@date as datetime)

SQL Fiddle with demo.

您可以将格式更新为 SQL Server 识别的格式并将字符串转换为一个语句中的日期时间:

You can update your format to one SQL Server recognises and cast the string to a datetime in one statement:

declare @date nvarchar(max) = '20130302T164800'

select cast(left(@date, 4)
  + '-' + substring(@date,5,2)
  + '-' + substring(@date,7,5)
  + ':' + substring(@date,12,2)
  + ':' + substring(@date,14,2) as datetime)

SQL Fiddle with demo.

这只是一个示例,您可以将其转换为 SQL Server 识别的任何格式,但这会将其转换为 ISO8601.基本上,将其转换为不同的格式以允许转换工作.

This is just an example, you could convert it to any format recognised by SQL Server, but this converts it to ISO8601. Basically, convert it to a different format to allow the conversion to work.

这篇关于将 ISO 格式的日期转换为 DATETIME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:56