简体   繁体   中英

Convert Datetime string to date in SQL Server

I have a datetime data from C# like this

2019-03-20T11:25:32.0342949

I tried to convert it to datetime using cast and it triggers error

select cast('2019-03-20T11:25:32.0342949' as date)

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

I guess its because of the T in the string.

I tried format also which of course doesn't work because its not identify it as date.

So how can I convert it properly to date. Without some substring methods to extract the date part.

You have to use DATETIME2 instead of DATETIME :

SELECT CAST('2019-03-20T11:25:32.0342949' AS DATETIME2) -- 2019-03-20 11:25:32.0342949

demo on dbfiddle.uk

The issue is the precision of the milliseconds part of your string value. You are using seven digits on the milliseconds part which is not possible on DATETIME . So you can do two things:

  • shorten the milliseconds part to three digits and use DATETIME
  • use DATETIME2 for more precision

Use the time , date , datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time , datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
source: https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql

There is also a comparison between DATETIME and DATETIME2 on StackOverflow:
DateTime2 vs DateTime in SQL Server

You have to take advantage of the CONVERT() method. For example, SELECT CONVERT(date, getdate()) , with date being the string you just mentioned. In your case, your datetime string takes up 10 letters of string, so you could also do SELECT CONVERT(VARCHAR(10), GETDATE(), 103) . The 3rd parameter is the datetime style you want to convert to.

If you need only date this will work

select cast('2019-03-20T11:25:32.0342949' as date) As DATE

If you need date and time this will work

select cast('2019-03-20T11:25:32.0342949' as datetime2) As DATE

Tried in Sql 15 Its working

在此处输入图片说明

You should not pass datetime as string from C#, this is the correct way to pass:

string sql = "SELECT * FROM table WHERE datevalue= @date";

SqlParameter dateParam = new SqlParameter("@date", SqlDbType.DateTime);
dateParam .Value = dateValue;

SqlCommand command = new SqlCommand(sql);
command.Parameters.AddWithValue("@date", dateParam );
// then execute the command...

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