简体   繁体   中英

Convert NVARCHAR to DATE SQL

I am having trouble converting this nvarchar to date: I want to convert '2021-02-01 00:00:00.0000000' nvarchar to 2021-02-01 date

   DECLARE @var nvarchar(255) = '2021-02-01 00:00:00.0000000'
   CONVERT(date, @var, 103)

I have used this convert function but I'm getting:

Conversion failed when converting date and/or time from character string

error. Any help on how to solve this problem?

Try 120 instead of 103 . 103 expects a string in the format d/m/y .

DECLARE @var nvarchar(255) = '2021-02-01 00:00:00.0000000';
SELECT CONVERT(date, @var, 120);

Result ( db<>fiddle ):

2021-02-01

Also:

  • Why nvarchar ? Dates don't need to support Unicode characters.

  • Try to get the source to correct the format to a standard, unambiguous format, like:

     yyyy-mm-ddThh:mm:ss.nnnnnnn yyyymmdd hh:mm:ss.nnnnnnn

Much more on dates: Dating Responsibly

You can CAST that format directly to a DATE or DATETIME2 type.

DECLARE @var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE @date date = CAST(@var AS DATE);

SELECT @var as var, @date as [date];

Or even CONVERT it without a format number.

DECLARE @var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE @datetime2 datetime2 = CONVERT(DATETIME2, @var);

SELECT @var as var, @datetime2 as [datetime2];

But to CAST or CONVERT it to a DATETIME , then it needs to be truncated.
The default format number is 121 (ODBC canonical with milliseconds)

DECLARE @var nvarchar(255) = '2021-02-01 00:00:00.0000000'
DECLARE @datetime datetime = CONVERT(datetime, LEFT(@var, 23), 121);

SELECT @var as var, @datetime as [datetime];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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