0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132

4 Answers4

2

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://learn.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

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
1

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.

Max Voisard
  • 1,685
  • 1
  • 8
  • 18
1

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

enter image description here

Tony Tom
  • 1,435
  • 1
  • 10
  • 17
0

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...
peeyush singh
  • 1,337
  • 1
  • 12
  • 23