I’m trying to compare 2 datetimes in asp.net but its ignoring the millisecond part.
I tried use linq:
messages.OrderBy(x => x.Date);
and also tried
messages.OrderBy(x => x.Date).ThenBy(x=>x.Date.Millisecond);
and also using sort
messages.Sort((x, y) => DateTime.Compare(x.Date, y.Date));
and tried convert the datetime with string format but its also ignoring the milliseconds.
The datetime field in the object is bringing the datetime with the milliseconds correctly.
I’m using Asp.net MVC3 with databases Informix, Oracle and SQL Server.
You’ve made a mistake somewhere, a
DateTimeis stored internally as a numberWhen you sort using a
DateTime, it is simply doing an integer sort using this underlying value. Therefore if yourDateTimeinstance has information about the number of milliseconds, it will be included in the sort. This can be demonstrated using code such as:Which gives the output:
Clearly demonstrating that sorting a list of datetimes correctly places the earlier number of milliseconds first.
Try it for yourself: http://rextester.com/HYQIM13679
As to why this isnt happening for you, thats impossible to answer as you’ve not supplied details of how you come by your list of objects containing a field with a
DateTimewhich you are sorting on. One possibility is that your source data is actually a string and you are using some variant ofDateTime.Parse/DateTime.ParseExactand have forgotton to specify that you wish to capture the millisecond part so they are being set to zero for every instance.