日期连贯计算

需求:从选中的日期列表中,合并日期连贯的日期,组成DateSpans对象的StartDate和EndDate属性,形成新的对象List<DateSpans>,代码和结果截图如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 
 5 namespace CalcDateRange
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             List<DateSpans> lstDateSpans = new List<DateSpans>();
12 
13             //选中的日期列表
14             List<DateTime> dates = new List<DateTime> {
15                 new DateTime(2017,9,2),new DateTime(2017,9,1),new DateTime(2017,9,5),new DateTime(2017,9,7)
16                 ,new DateTime(2017,9,8),new DateTime(2017,9,8)
17             };
18 
19             //把日期按从小到大排序
20             dates = dates.OrderBy(p => p.Date).ToList();
21 
22             if (dates.Count > 0)
23             {
24                 Dictionary<DateTime, DateTime> timeSpans = new Dictionary<DateTime, DateTime>();
25                 DateTime previous = DateTime.MinValue;
26                 DateTime current = DateTime.MinValue;
27                 DateTime currentKey = dates[0];
28                 DateSpans ds = new DateSpans();
29 
30                 for (int i = 0; i < dates.Count; i++)
31                 {
32                     if (!timeSpans.ContainsKey(currentKey))
33                     {
34                         timeSpans.Add(currentKey, DateTime.MinValue);
35                     }
36                     if (i > 0)
37                     {
38                         previous = dates[i - 1];
39                     }
40                     current = dates[i];
41                     if (previous != DateTime.MinValue && current.Subtract(previous).Days > 1)
42                     {
43                         timeSpans[currentKey] = previous;
44                         currentKey = current;
45                         timeSpans.Add(currentKey, DateTime.MinValue);
46                     }
47 
48                     if (i == dates.Count - 1)
49                     {
50                         timeSpans[currentKey] = current;
51                     }
52                 }
53                 if (timeSpans.Count > 0)
54                 {
55                     foreach (var item in timeSpans)
56                     {
57                         ds = new DateSpans();
58                         ds.StartDate = item.Key;
59                         ds.EndDate = item.Value;
60                         lstDateSpans.Add(ds);
61 
62                         Console.WriteLine(string.Format("Start Date:{0} End Date:{1}", item.Key.ToShortDateString(), item.Value.ToShortDateString()));
63                     }
64                 }
65             }
66 
67             Console.ReadKey();
68         }
69 
70         class DateSpans
71         {
72             public DateTime StartDate { get; set; }
73             public DateTime EndDate { get; set; }
74         }
75     }
76 }

 运行结果:
  

原文地址:https://www.cnblogs.com/GerryGe/p/7472514.html