DateTime.Now is millisecond different

In my application, I am assigning DateTime.Now to a new DateTime. then I assign it to the value and write it to the database. But then, when I return from the database and compare the variable with the new date assigned earlier, it differs from a couple of milliseconds.

Does anyone have an idea why this is happening?

eg.

DateTime var1 = DateTime.Now; Object1.DateTime = var1; Database.SaveObject = var1 Object2 = Database.FindObjectById(objectId); Assert.AreEqual(var1, Object2.DateTime); 
+4
source share
2 answers

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

Switching the column type to datetime2 should help, since its resolution is 100 nanoseconds.

+7
source

Do you use MS SQL Server, sometimes the data is accurate only up to 3 milliseconds, so you will see that the figure is rounded to the nearest 3 milliseconds.

See MSDN - TSQL DateTime

You can use DateTime2 if you have SQL2008 or later.

+2
source

All Articles