2014-11-21 87 views
1

我试图使用SQL CONVERT命令将VARCHAR转换为SQL Server 2012中的DATETIME。我按照说明操作,我想使用日期/这个MSDN网页上描述的时间格式:http://msdn.microsoft.com/en-us/library/ms187928.aspxSQL中将VARCHAR转换为DATETIME时出现的问题

在此基础上,格式#127的描述如下:

  • ISO8601 with time zone Z.
  • yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
  • When the value for milliseconds (mmm) is 0, the millisecond value is not displayed. For example, the value '2012-11-07T18:26:20.000 is displayed as '2012-11-07T18:26:20'.
  • The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example: 2006-12-12T23:45:12-08:00.

然而,当我尝试实际进行转换(以下这种格式),它失败...

SELECT CONVERT(datetime, '2014-07-14T10:00:00.000-08:00', 127) 

...,出现以下错误:

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

任何人都知道这是为什么不工作?

编辑:例如不工作之一:

SELECT CONVERT(datetime, '2006-12-12T23:45:12-08:00', 127) 

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

回答

1

因为它是在它时区一个字符串,你需要将其转换为DATETIMEOFFSET类型:

SELECT CONVERT(DATETIMEOFFSET, '2014-07-14T10:00:00.000-08:00', 127) 

(No column name) 
---------------------------------- 
2014-07-14 10:00:00.0000000 -08:00 

这工作得很好。一旦你有了,你可以根据需要将它转换为当地的DATETIME,例如。与

DECLARE @DateTimeOffset DATETIMEOFFSET 
CAST(@DateTimeOffset AS DATETIME) 

或价值与

SELECT SWITCHOFFSET(@DateTimeOffset, '+01:00') 
+0

切换到另一个时区这工作,谢谢!我想我需要继续阅读脚注:-x – 2014-11-21 22:45:20