Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now differs a millisecond

Tags:

c#

datetime

time

On my application i assign a DateTime.Now to a new DateTime. then i assign it to a value and write it to the database. But then when i get it back from the database and compare the variable to the new datetime assigned earlier it differs with a couple of milliseconds.

Anyone has an idea why this happens?

E.g.

DateTime var1 = DateTime.Now;
Object1.DateTime = var1;

Database.SaveObject = var1

Object2 = Database.FindObjectById(objectId);

Assert.AreEqual(var1, Object2.DateTime);
like image 743
Nicolas Pierre Avatar asked Jan 14 '23 09:01

Nicolas Pierre


2 Answers

This is most likely an issue with the precision of DB's datetime column: it does not have enough accuracy to store the time up to a millisecond. When you use datetime, the time portion is rounded to increments of .000, .003, or .007 seconds.

Switching column's type to datetime2 should help, because its resolution is 100 nanoseconds.

like image 170
Sergey Kalinichenko Avatar answered Jan 25 '23 23:01

Sergey Kalinichenko


Are you using MS SQL Server, datetimes are only precise to 3 milliseconds so you will find that the figure is rounding to the nearest 3 milliseconds.

See MSDN - TSQL DateTime

You may want to use DateTime2 if you have SQL2008 or later.

like image 39
Bob Vale Avatar answered Jan 25 '23 23:01

Bob Vale