Convert Character string ISO date to DateTime and vice-versa

Here’s how to convert ISO8601 character data to DateTime and DateTime back to ISO8601 in SQL Server

DECLARE @IsoDate nvarchar(35)
SET @IsoDate = '2010-03-16T19:20:30.45123+01:00'

-- CONVERT TO DATETIME in SQL 2008
SELECT CAST(CONVERT(datetimeoffset, @IsoDate) AS datetime) as SQL2008

-- CONVERT TO DATETIME in SQL 2005 and earlier
SELECT CAST(LEFT(@IsoDate, 23) AS datetime) as SQL2005


-- CONVERT DateTime to ISO Date format
SELECT CONVERT(nvarchar(35), GETDATE(), 127) as ISO8601 ;

OUTPUT

image

1 comment:

  1. The conversion completely ignores the timezone offset information: the input is explicitly one hour off UTC, but the output is 19:20:30 in whatever timezone your server happens to be running.

    ReplyDelete