public class DateTimeArea
{
/// <summary>
/// 开始时间
/// </summary>
public DateTime startTime { get; set; }
/// <summary>
/// 开始时间
/// </summary>
public DateTime endTime { get; set; }
}
class Program
{
static void Main(string[] args)
{
DateTime starttime = DateTime.Parse("2020-3-30 18:50:44");
DateTime endtime = DateTime.Parse("2020-4-2 19:50:47");
List<DateTimeArea> list = new List<DateTimeArea>();
//分段输出两个时间
//如果时间是一天内
if (starttime.Day == endtime.Day)
{
//如果是同一天,按照同一天走
//开始就是开始,结束就是结束
list.Add(new DateTimeArea() { startTime = starttime, endTime = endtime });
}
else
{
//开头
DateTime headStartTime = starttime;
DateTime headEndTime = new DateTime(starttime.Year, starttime.Month, starttime.Day, 23, 59, 59);
list.Add(new DateTimeArea() { startTime = headStartTime, endTime = headEndTime });
//结尾
DateTime bootStartTime = new DateTime(endtime.Year, endtime.Month, endtime.Day, 0, 0, 0);
DateTime bootEndTime = endtime;
//需要遍历的天
int day = (bootStartTime - headEndTime).Days;
if (day > 0)
{
for (int i = 0; i < day; i++)
{
DateTime CenterEnd = headEndTime.AddDays(i + 1);
DateTime CenterStart = new DateTime(CenterEnd.Year, CenterEnd.Month, CenterEnd.Day, 0, 0, 0);
list.Add(new DateTimeArea() { startTime = CenterStart, endTime = CenterEnd });
}
}
list.Add(new DateTimeArea() { startTime = bootStartTime, endTime = bootEndTime });
}
Console.WriteLine($"分割的开始时间{starttime} 结束时间{endtime}");
Console.WriteLine();
foreach (var item in list)
{
Console.WriteLine($"开始时间{item.startTime} 结束时间{item.endTime}");
}
Console.ReadLine();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/18e130d82c70765354defe05ffa44102.png)