namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
DateTime startDate = new DateTime(2020, 1, 1);
DateTime endDate = new DateTime(2023, 12, 31);
List<int> years = DateRangeYears.GetYearsBetween(startDate, endDate);
foreach (int year in years)
{
Console.WriteLine(year);
}
Console.ReadKey();
}
}
public class DateRangeYears
{
/// <summary>
/// 获取时间范围内所有年份
/// </summary>
/// <param name="startDate">开始时间</param>
/// <param name="endDate">结束时间时间</param>
/// <returns>年份(2020、2021、2022、···)</returns>
public static List<int> GetYearsBetween(DateTime startDate, DateTime endDate)
{
List<int> years = new List<int>();
for (DateTime currentDate = startDate; currentDate <= endDate; currentDate = currentDate.AddYears(1))
{
years.Add(currentDate.Year);
}
return years;
}
}
}
09-17
1179
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-14
06-07