简体   繁体   English

C#DateTime操作

[英]C# DateTime manipulation

I have a list of dates for an event in the following format 我有以下格式的活动日期列表

13/04/2010 10:30:00
13/04/2010 13:30:00
14/04/2010 10:30:00
14/04/2010 13:30:00
15/04/2010 10:30:00
15/04/2010 13:30:00
16/04/2010 10:30:00
17/04/2010 11:00:00
17/04/2010 13:30:00
17/04/2010 15:30:00

How can i have the list be output, so that the date is only displayed once followed by the times for that date, so the above list would look like something like this: 我如何才能输出列表,以便日期仅显示一次,然后显示该日期的时间,因此上面的列表看起来像这样:

13/04/2010 
10:30:00
13:30:00

14/04/2010 
10:30:00
13:30:00

15/04/2010 
10:30:00
13:30:00

16/04/2010 
10:30:00

17/04/2010 
11:00:00
13:30:00
15:30:00

Well I don't know about the display side, but the grouping side is easy if you're using .NET 3.5+: 我不知道显示方面,但是如果您使用的是.NET 3.5+,则分组方面很容易:

var groups = list.GroupBy(dateTime => dateTime.Date);

foreach (var group in groups)
{
    Console.WriteLine("{0}:", group.Key);
    foreach(var dateTime in group)
    {
        Console.WriteLine("  {0}", dateTime.TimeOfDay);
    }
}
        List<DateTime> dateTimes = new List<DateTime>();
        Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
        foreach (DateTime t in dateTimes)
        {
            if (!data.ContainsKey(t.ToShortDateString()))
            {
                data.Add(t.ToShortDateString(), new List<string>());
            }

            data[t.ToShortDateString()].Add(t.ToShortTimeString());
        }

        foreach (string key in data.Keys)
            data[key].Sort();

        foreach (var pair in data)
        {
            Console.WriteLine(pair.Key);
            foreach (string time in pair.Value)
                Console.WriteLine(time);

            Console.WriteLine();
        }

If you have your dates in something like a List<DateTime> then you could do this: 如果您的日期使用类似List <DateTime>的日期,则可以执行以下操作:

DateTime dtTemp = DateTime.MinValue;
StringBuilder sb = new StringBuilder();
foreach(DateTime dt in MyDateList)
{
    if (dt == dtTemp) sb.AppendLine(dt.ToString("HH:mm:ss"));
    else
    {
        dtTemp = dt;
        sb.AppendLine();
        sb.AppendLine(dt.ToString("dd/MM/yyyy HH:mm:ss"));
    }
}
Console.WriteLine(sb.ToString().Trim());

Edit: Trim output to eliminate blank first line. 编辑:修剪输出以消除空白的第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM