如何对日期进行数字排序
本文关键字:数字 排序 日期 | 更新日期: 2023-09-27 18:30:04
我想对一些日期进行数字排序(而不是Date.compare())
我应该将日期转换为什么类型,以便在客户端(JS)上对表进行排序?
int?时间戳?
如何?
使用DateTime.Ticks
,它是long
类型。
使用Ticks属性获取DateTime的数字表示。以下是一个按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();
}
它产生这个输出:
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...
您不需要将日期转换为任何内容来进行排序:
new[] { DateTime.Now, DateTime.Now.AddDays(-1) }.OrderBy(d => d);
只需像这样对其进行排序
Array.Sort(datetimearr[]);
使用此如何按降序对DateTime对象的ArrayList进行排序?
只需将它们添加到基于IEnumerable<DateTime>
的集合中,然后使用LINQ对它们进行排序,类似于:
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);
您不应该使用DateTime.Ticks
,因为日期是可比较的。