gpt4 book ai didi

c# - 转换日期列表以便在包含连续日期的情况下按组显示的最佳方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:44 25 4
gpt4 key购买 nike

我有一个日期列表

 var list = new List<DateTime>();
list.Add(new DateTime(2014, 1,1);
list.Add(new DateTime(2014, 1,2);
list.Add(new DateTime(2014, 1,3);
list.Add(new DateTime(2014, 1,5);
list.Add(new DateTime(2014, 1,6);
list.Add(new DateTime(2014, 1,11);

并且某些日期是连续的。我想将连续的日期组合在一起并在 UI 上将其呈现为:

"Jan 1-3, 2015; Jan 5-6, 2015; Jan 11, 2015"

进行此列表转换的正确方法是什么?没有这个。我会做这样的事情:

 var display = String.Join(";", list.Select(r=>r.ToString("dd-MMM-yyyy"));

最佳答案

void Main()
{
var list = new List<DateTime>();
list.Add(new DateTime(2014, 1, 1));
list.Add(new DateTime(2014, 1, 2));
list.Add(new DateTime(2014, 1, 3));
list.Add(new DateTime(2014, 1, 5));
list.Add(new DateTime(2014, 1, 6));
list.Add(new DateTime(2014, 1, 11));

string output = string.Join("; ", GetRanges(list).Select(FormatRange));

Console.WriteLine(output);
// Jan 1–3, 2014; Jan 5–6, 2014; Jan 11, 2014
}

private string FormatRange (DateRange range)
{
if (range.Start.Year != range.End.Year)
return range.Start.ToString("MMM d, yyyy") + " – " + range.End.ToString("MMM d, yyyy");
else if (range.Start.Month != range.End.Month)
return range.Start.ToString("MMM d") + " – " + range.End.ToString("MMM d, yyyy");
else if (range.Start.Day != range.End.Day)
return range.Start.ToString("MMM d") + "–" + range.End.ToString("d, yyyy");
else
return range.Start.ToString("MMM d, yyyy");
}

private List<DateRange> GetRanges (IEnumerable<DateTime> dates)
{
List<DateRange> ranges = new List<DateRange>();
DateRange current = null;
DateTime? previous = null;

foreach (DateTime date in dates)
{
if (!previous.HasValue)
current = new DateRange() { Start = date };
else if ((date - previous.Value).Days > 1)
{
current.End = previous.Value;
ranges.Add(current);
current = new DateRange() { Start = date };
}
previous = date;
}

if (previous.HasValue)
{
current.End = previous.Value;
ranges.Add(current);
}

return ranges;
}

public class DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}

关于c# - 转换日期列表以便在包含连续日期的情况下按组显示的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com