计算2个日期之间的月份的最佳方法是什么。我不需要数字,但实际的月数。
最好的方法是什么。
Given 2 dates May 1 2008 and August 3 2008 , I should get May , June , July, August.
or
Nov 1st 2009 and April 3rd 2010 ==> Nov ,Dec, Jan ,Feb , Mar,April .
答案 0 :(得分:2)
考虑多年:
DateTime one = new DateTime(2006, 06, 16), two = new DateTime(2007, 08, 23);
if (two > one)
{
int firstMonth = one.Month;
int secondMonth = two.Month + 12 * (two.Year - one.Year);
var months = new List<string>();
for (int i = firstMonth; i <= secondMonth; i++)
{
months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName((i -1) % 12 + 1));
}
}
当然,建立逆转它的案例非常简单。
答案 1 :(得分:2)
DateTime start = new DateTime(2009, 11, 1);
DateTime end = new DateTime(2010, 4, 1);
for(var dt = start; dt <= end; dt = dt.AddMonths(1))
{
Console.WriteLine(dt.ToString("MMM",CultureInfo.InvariantCulture));
}