如何选择每月的最新日期时间

本文关键字:最新 日期 时间 何选择 选择 | 更新日期: 2023-09-27 17:55:27

我必须实现一种算法,该算法接收日期时间列表,并恢复每个月的最新日期时间,但我不知道该怎么做。例:

29/06/2016 -> Lastest date of june
27/06/2016
05/05/2016 -> Lastest date of may
15/04/2016 -> Lastest date of april
13/04/2016
...

预期成果

29/06/2016
05/05/2016
15/04/2016

如何选择每月的最新日期时间

您询问的是日期列表中每月的最大日期。您可以使用 LINQ 通过使用 GroupByMax 来获得它,例如:

 var maxDatesPerMonth=from date in dates
                      group date by new {date.Year,date.Month} into months
                      select months.Max();

var maxDatesPerMonth=dates.GroupBy(date=>new {date.Year,date.Month})
                          .Select(months=>months.Max());

你可以用 LINQ 解决这个问题。

伪代码:

dateList.Where(x => x.Month == 6).Max()

这将为您提供 6 月的最晚日期。

请确保使用日期时间类型的正确属性,而不是 *.Month 。您可能还需要指定.Max(),也许带有.Select(x => x.Day).Max()

尽管如此:LINQ 是要走的路。希望对您有所帮助。

试试这个...

 class Program
{
    static void Main(string[] args)
    {
        var dateTimes = new[]
        {
            new DateTime(2016, 06, 29 ),
            new DateTime(2016, 06, 27 ),
            new DateTime(2016, 05, 05 ),
            new DateTime(2016, 04, 15 ),
            new DateTime(2016, 04, 13 )
        };
        var years = dateTimes.GroupBy(x => x.Year).OrderByDescending(x => x.Key);
        foreach (IGrouping<int, DateTime> grouping in years)
        {
            var months = grouping.GroupBy(x => x.Month);
            foreach (IGrouping<int, DateTime> month in months)
            {
                Console.WriteLine(month.First());
            }
        }
        Console.ReadLine();
    }
}

这将输出以下内容...

29/06/2016 00:00:00
05/05/2016 00:00:00
15/04/2016 00:00:00