4

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);
Nicolas Pierre
  • 1,174
  • 1
  • 21
  • 39

2 Answers2

7

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

Bob Vale
  • 18,094
  • 1
  • 42
  • 49