以特定方式分割日期范围的问题



假设我有两个DateTime对象,我想把日期范围分成以天为单位的块大小;

var date1 = new DateTime(2022, 3, 1, 8, 30, 0);
var date2 = new DateTime(2022, 3, 5, 11, 30, 0);

这个方法差不多完成了任务;

public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}

并给出如下的结果集;

{(1.03.2022 08:30:00, 2.03.2022 08:30:00)}
{(2.03.2022 08:30:00, 3.03.2022 08:30:00)}
{(3.03.2022 08:30:00, 4.03.2022 08:30:00)}
{(4.03.2022 08:30:00, 5.03.2022 08:30:00)}
{(5.03.2022 08:30:00, 5.03.2022 11:30:00)}

我真正需要的是这样一个结果集;

{(1.03.2022 08:30:00, 2.03.2022 00:00:00)}
{(2.03.2022 00:00:00, 3.03.2022 00:00:00)}
{(3.03.2022 00:00:00, 4.03.2022 00:00:00)}
{(4.03.2022 00:00:00, 5.03.2022 00:00:00)}
{(5.03.2022 00:00:00, 5.03.2022 11:30:00)}

有什么好主意吗?

您可以使用DateTime.Date属性截断时间部分。

替换以下两行:

yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;

:

yield return Tuple.Create(start, chunkEnd.Date);
start = chunkEnd.Date;

如果它不是集合中的第一项或最后一项,您可以将chuckend的时间部分替换为:

chunkEnd = new DateTime(chunkEnd.Year, chunkEnd.Month, chunkEnd.Day, 00, 00, 00);

最新更新