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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With