Rafael Kayser Smiderle
Rafael Kayser Smiderle

Reputation: 690

Compare datetime with millisecond precision

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.

Upvotes: 3

Views: 8872

Answers (1)

Jamiec
Jamiec

Reputation: 136094

You've made a mistake somewhere, a DateTime is stored internally as a number

Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar (source)

When you sort using a DateTime, it is simply doing an integer sort using this underlying value. Therefore if your DateTime instance has information about the number of milliseconds, it will be included in the sort. This can be demonstrated using code such as:

var dates = new[]{
    new DateTime(2013,1,31,12,0,0,10),
        new DateTime(2013,1,31,12,0,0,20),
        new DateTime(2013,1,31,12,0,0,5)
};

foreach(var date in dates)
{
    Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
}

Console.WriteLine("-------------");

foreach(var date in dates.OrderBy(dt => dt))
{
    Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
}

Which gives the output:

2013-01-31 12:00:00.010
2013-01-31 12:00:00.020
2013-01-31 12:00:00.005
-------------
2013-01-31 12:00:00.005
2013-01-31 12:00:00.010
2013-01-31 12:00:00.020

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 DateTime which you are sorting on. One possibility is that your source data is actually a string and you are using some variant of DateTime.Parse / DateTime.ParseExact and have forgotton to specify that you wish to capture the millisecond part so they are being set to zero for every instance.

Upvotes: 5

Related Questions