1、找出时间段一之间的所有月份列表list<int> list1,可以参考下这个:http://blog.csdn.net/mh942408056/article/details/7077467
2、找出时间段二之间的所有月份列表list<int> list2
3、求list1和list2的交集再去重复,这几个月就是重复的月了。var intersectedList = list1.Intersect(list2);
将两个时间段的月份放进List<int> 中 => monthList 然后定义一个装重复月份的集合List<int> => repeatMonthList monthList.GroupBy(x=>x).ForEach((x) => { if(x.Count()>=2) { repeatMonthList.Add(x.Key); } }
1 DateTime dt1 = Convert.ToDateTime("2016-1-1"); 2 DateTime dt2 = Convert.ToDateTime("2016-12-31"); 3 DateTime dt3 = Convert.ToDateTime("2016-5-1"); 4 DateTime dt4 = Convert.ToDateTime("2017-5-31"); 5 List<Test> testlist1 = getDetailMonth(dt1, dt2); 6 List<Test> testList2 = getDetailMonth(dt3, dt4); 7 List<Test> sameMonthlist = new List<Test>(); 8 //相同的月份 9 foreach (Test test1 in testlist1) 10 { 11 foreach (Test test2 in testList2) 12 { 13 if (test1.Year == test2.Year && test1.Month == test2.Month) 14 { 15 Test test = new Test(); 16 test.Year = test2.Year; test.Month = test2.Month; 17 sameMonthlist.Add(test); 18 } 19 } 20 } 21 22 public List<Test> getDetailMonth(DateTime dt1, DateTime dt2) 23 { 24 List<Test> testList = new List<Test>(); 25 for (int i = 1; i < (dt2.Year - dt1.Year) * 12 + dt2.Month - dt1.Month; i++) 26 { 27 Test test = new Test(); 28 if (dt2.Year > dt1.Year) 29 { 30 if (dt1.Month + i ==13) 31 { 32 for (int j = 1; j < dt2.Month; j++) 33 { 34 Test test1 = new Test(); 35 test1.Year = dt2.Year; 36 test1.Month = j; 37 testList.Add(test1); 38 } 39 } 40 else if (dt1.Month + i <= 12) 41 { 42 test.Year = dt1.Year; 43 test.Month = dt1.Month + i; 44 testList.Add(test); 45 } 46 } 47 else 48 { 49 test.Year = dt1.Year; 50 test.Month = dt1.Month + i; 51 testList.Add(test); 52 } 53 } 54 return testList; 55 } 56 57 public class Test 58 { 59 public int Year { get; set; } 60 61 public int Month { get; set; } 62 }