Search code examples
c#datetimesqldatetime

JavaScript datetime stamp to SqlDateTime with milliseconds


I have JS datetime stamp being recorded with full millisecond fidelity 1/1000. (using SQL I understand the precision is 1/300)

I have been using .NET System.DateTime struct and I have not been seeing the milliseconds being stored in SQL.

...   
 [ResponseTimeStamp] DATETIME         NOT NULL,
...

with c#

//TimeCompleted is epoc 

    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    qr.ResponseTimeStamp = dtDateTime.AddMilliseconds(item.Responses.TimeCompleted); 

I am now trying to use System.Data.SqlTypes.SqlDateTime with

SqlDateTime dtDateTime = new SqlDateTime(1970, 1, 1, 0, 0, 0, 0);
qr.ResponseTimeStamp = SqlDateTime.Add(dtDateTime, item.Responses.TimeCompleted);

issue is that the method is throwing the exception:

"message": "The best overloaded method match for 'System.Data.SqlTypes.SqlDateTime.Add(System.Data.SqlTypes.SqlDateTime, System.TimeSpan)'

I've tried converting from epoc to TimeSpan, but the signature requires a TimeSpan which i create but still throws an exception.

TimeSpan newSpan = new TimeSpan(0, 0, 0, 0, item.Responses.TimeCompleted);

The best overloaded method match for 'System.Data.SqlTypes.SqlDateTime.Add(System.Data.SqlTypes.SqlDateTime, System.TimeSpan)' has some invalid arguments


Solution

  • If you need to store the time down to the millisecond then you should be using a datetime2 or a datetimeoffset for your data.

    Both these types allow for accuracy down to the millisecond unlike DateTime which only has a resolution of 3 milliseconds.