gpt4 book ai didi

c# - 速记日期

转载 作者:太空狗 更新时间:2023-10-29 23:34:42 25 4
gpt4 key购买 nike

假设您有一个如下所示的日期字符串:

11/15/2010, 12/1/10, 12/2/10, 12/3/10, 12/4/10, 12/9/10

你会如何像下面这样缩短这个字符串(或类似的东西)

11/15/2010, 12/1-4, 9/10

因为想象连续 30 天,看到 12/1-31/10 比列出所有日期要好。

只是为了让它更紧凑一点?

谢谢,杆。

最佳答案

public class so_4413380
{
private class DateGroup
{
public IList<DateTime> Dates { get; set; }

public DateTime First
{
get { return Dates.OrderBy(d => d).FirstOrDefault(); }
}

public DateTime Last
{
get { return Dates.OrderBy(d => d).LastOrDefault(); }
}

public DateGroup()
{
Dates = new List<DateTime>();
}
}

public void Execute()
{
var dateTimeFormat = CultureInfo.GetCultureInfo("en-US").DateTimeFormat;
var dates = new[] { "11/15/2010", "12/1/10", "12/2/10", "12/3/10", "12/4/10", "12/9/10" };
var realDates = dates.Select(s => DateTime.Parse(s, dateTimeFormat));
var dateGroups = new List<DateGroup>();

DateTime lastDate = DateTime.MinValue;
foreach (var date in realDates.OrderBy(d => d))
{
if (date.Month == lastDate.Month && (date - lastDate).Days <= 1)
{
var dateGroup = dateGroups.LastOrDefault();
dateGroup.Dates.Add(date);
}
else
{
var dateGroup = new DateGroup();
dateGroups.Add(dateGroup);

dateGroup.Dates.Add(date);
}

lastDate = date;
}

foreach (var dateGroup in dateGroups)
{
if (dateGroup.Dates.Count == 1)
{
Console.WriteLine(dateGroup.First.ToString(dateTimeFormat.ShortDatePattern, dateTimeFormat));
}
else
{
int firstDay = dateGroup.First.Day;
int lastDay = dateGroup.Last.Day;

var dateString = dateTimeFormat.ShortDatePattern.Replace("d", firstDay + "-" + lastDay);

Console.WriteLine(dateGroup.First.ToString(dateString, dateTimeFormat));
}
}

Console.ReadLine();
}
}

生产

11/15/2010
12/1-4/2010
12/9/2010

关于c# - 速记日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413380/

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