-4

I want to sort some dates numerically (not Date.compare())

Into what type should I convert the dates, so I could sort a table on client side (JS)?

int? timestamp?

and how?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

5 Answers5

2

Use DateTime.Ticks it is of long type.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • I'd be careful with this. According to http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx -- *It does not include the number of ticks that are attributable to leap seconds.* – Yuck Apr 04 '12 at 15:18
  • 1
    Ticks represents DateTime value. And actually Ticks used to compare dates. See Equals or CompareTo implementations. – Sergey Berezovskiy Apr 04 '12 at 15:21
  • 1
    @Yuck DateTime doesn't handle leap seconds at all, so I don't see why you'd want to take them into account when sorting. – phoog Apr 04 '12 at 15:32
  • Downvoter, it would be great to see what is wrong with my answer, please add some comments - it may be usefull to me and other users – Sergey Berezovskiy Jun 15 '14 at 08:15
2

Use the Ticks property to get a numerical representation of a DateTime. Here's a sample program that sorts them by Ticks:

    static void Main(string[] args)
    {
        var dates = new List<DateTime> { new DateTime(2011, 5, 31), new DateTime(2012, 7, 31), new DateTime(2010, 1, 31) };
        dates.OrderBy(d => d.Ticks).ToList().ForEach(d => Console.WriteLine(d.ToString()));

        Console.WriteLine("Press ENTER to exit...");
        Console.ReadLine();
    }

which produces this output:

1/31/2010 12:00:00 AM
5/31/2011 12:00:00 AM
7/31/2012 12:00:00 AM
Press ENTER to exit...
Aaron Daniels
  • 9,563
  • 6
  • 45
  • 58
1

You do not need to covert date to anything to sort it:

new[] { DateTime.Now, DateTime.Now.AddDays(-1) }.OrderBy(d => d);
the_joric
  • 11,986
  • 6
  • 36
  • 57
0

Just sort it like this

Array.Sort(datetimearr[]);

Use this How to sort ArrayList of DateTime objects in descending order?

Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

Just add them to a collection based on IEnumerable<DateTime> and use LINQ to sort them, something like:

using System.Collections.Generic;
using System.Linq

...

List<DateTime> dates = new List<DateTime>();

dates.Add(new DateTime(2012, 04, 01));
dates.Add(new DateTime(2012, 04, 05));
dates.Add(new DateTime(2012, 04, 04));
dates.Add(new DateTime(2012, 04, 02));
dates.Add(new DateTime(2012, 04, 03));

List<DateTime> orderedDates = dates.OrderBy(d => d);

You shouldn't need to use DateTime.Ticks as dates are comparible.

Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69