数据库数据列为2021-05的字符串格式,想取2021-05-2021-07数据库月份范围区间符合条件的数据,由于用的是传统的EF查询写法,找了大半天,发现没找到List条件开始时间和结束时间的月份集合,最终参考辅助方法解决了问题,赶紧发出来以防下次踩坑。
/// <summary> /// 计算年月区间 /// </summary> public class ComputeDate { /// <summary> /// 年 /// </summary> public int Year { get; set; } /// <summary> /// 月 /// </summary> public int Month { get; set; } } /// <summary> /// 计算区间月份 /// </summary> /// <param name="startYear">开始年</param> /// <param name="startMonth">开始月</param> /// <param name="endYear">结束年</param> /// <param name="endMonth">结束月</param> /// <returns></returns> public List<string> ComputeMonth(int startYear, int startMonth, int endYear, int endMonth) { List<ComputeDate> ComputeDateList = new List<ComputeDate>(); //计算的区间结果存放在集合 List<string> ymList = new List<string>(); if (startYear <= endYear) { int ComputeYear = endYear - startYear; //计算开始年和结束年差值 if (ComputeYear > 0)//跨年情况 { //循环开始年到结束年 for (int i = startYear; i <= startYear + ComputeYear; i++) { if (i == endYear) { for (int lastYear = 1; lastYear <= endMonth; lastYear++) { ComputeDateList.Add(new ComputeDate() { Year = i, Month = lastYear }); } } else { if (i == startYear) { for (int lastMonth = startMonth; lastMonth <= 12; lastMonth++) { ComputeDateList.Add(new ComputeDate() { Year = i, Month = lastMonth }); } } else { for (int quyue = 1; quyue <= 12; quyue++) { ComputeDateList.Add(new ComputeDate() { Year = i, Month = quyue }); } } } } } else { //同年情况 for (int i = startMonth; i <= endMonth; i++) { ComputeDateList.Add(new ComputeDate() { Year = startYear, Month = i }); } } foreach (var item in ComputeDateList) { //发现月份会少0,判断小于10月补0 var months = ""; if (item.Month<10) { months = "0"+item.Month; } else{ months = Convert.ToString(item.Month); } ymList.Add(item.Year + "-" + months); } } return ymList; } /// <summary> /// 条件过滤 /// </summary> /// <param name="query"></param> /// <returns></returns> public IQuery<BankCorpOCRecord> ConditionFilter(IQuery<BankCorpOCRecord> query) { if (!string.IsNullOrEmpty(OrgName)) { query = query.Where(x => x.OrgName.Contains(OrgName)); } if (!string.IsNullOrEmpty(BankAccount)) { query = query.Where(x => x.BankAccount == BankAccount); } if (!string.IsNullOrEmpty(BankAccountName)) { query = query.Where(x => x.BankAccountName.Contains(BankAccountName)); } if (!string.IsNullOrEmpty(beginTime)) { int startYear = Convert.ToInt32(beginTime.Substring(0,4)); //开始年份 int startMonth = Convert.ToInt32(beginTime.Substring(5, 2)); //开始月份 int endYear = Convert.ToInt32(endTime.Substring(0, 4)); //结束年份 int endMonth = Convert.ToInt32(endTime.Substring(5, 2)); //结束月份 ReconciliationDataHelper helper = new ReconciliationDataHelper(); var PeriodList = helper.ComputeMonth(startYear, startMonth, endYear, endMonth); query = query.Where(x => PeriodList.Contains(x.PERIOD)); } return query; }