Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nvarchar ISO-8601 date to datetime in SQL Server

hopefully a quick one this.

The below doesn't work:

DECLARE @stringDate nvarchar(50)
SET @stringDate = '0001-01-01T12:00:00'

SELECT 
    @stringDate AS StringDate,
    CONVERT(datetime, @stringDate, 126) AS ConvertedDate

Produces the error: The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.

What's the simplest way of achieving the conversion?

Thanks

like image 475
NiceYellowEgg Avatar asked Apr 18 '12 10:04

NiceYellowEgg


People also ask

Can we convert nvarchar to datetime in SQL?

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

What is cast () and convert () functions in SQL Server?

The T-SQL language offers two functions to convert data from one data type to a target data type: CAST and CONVERT. In many ways, they both do the exact same thing in a SELECT statement or stored procedure, but the SQL Server CONVERT function has an extra parameter to express style.

How do I convert a date to a date in SQL?

You can convert a DATETIME to a DATE using the CONVERT function. The syntax for this is CONVERT (datetime, format).


2 Answers

Type Datetime does not support the year 0001. Supported range is 1753 to 9999.
As a workaround you can use type DateTime2 instead

SELECT 
    @stringDate AS StringDate,
    CONVERT(datetime2, @stringDate, 126) AS ConvertedDate
like image 138
Magnus Avatar answered Sep 22 '22 21:09

Magnus


It doesn't work because for DATETIME data type the

Date range [is] January 1, 1753, through December 31, 9999.

You have to use the new data type DATETIME2:

SET ANSI_WARNINGS OFF;  --Not recommended
SET ARITHABORT OFF;     --Not recommended
DECLARE @stringDate nvarchar(50)
SET @stringDate = '0001-01-01T12:00:00'

SELECT 
    @stringDate AS StringDate,
    CONVERT(datetime, @stringDate, 126) AS Converted_DATETIME,
    CONVERT(datetime2, @stringDate, 126) AS Converted_DATETIME2_A,
    CONVERT(datetime2(0), @stringDate, 126) AS Converted_DATETIME2_B

Results:

StringDate          Converted_DATETIME Converted_DATETIME2_A  Converted_DATETIME2_B
------------------- ------------------ ---------------------- ----------------------
0001-01-01T12:00:00 NULL               0001-01-01 12:00:00.00 0001-01-01 12:00:00
Arithmetic overflow occurred.

Note: you may change the default precision for DATETIME2 data type if your date/time values doesn't have "fractional seconds precision": DATETIME2(0).

like image 39
Bogdan Sahlean Avatar answered Sep 21 '22 21:09

Bogdan Sahlean