/// <summary>
/// 獲取兩個時間段之間的月份
/// </summary>
/// <param name="startTime">開始月份</param>
/// <param name="endTime">結束月份</param>
/// <returns>月份字符串</returns>
public static string DateFiledMonths(string startTime, string endTime)
{
try
{
int index = 0;
string filed = string.Empty;
DateTime c1 = Convert.ToDateTime(Convert.ToDateTime(startTime).ToString("yyyy-MM"));
DateTime c2 = Convert.ToDateTime(Convert.ToDateTime(endTime).ToString("yyyy-MM"));
if (c1 > c2)
{
DateTime tmp = c1;
c1 = c2;
c2 = tmp;
}
while (c2 >= c1)
{
index++;
if (index > 12) // 判斷是否大於12個月,如果大於,跳出 www.2cto.com
break;
filed += c1.ToString("yyyy-MM") + "|";
c1 = c1.AddMonths(1);
}
return filed.TrimEnd('|');
}
catch { return null; }
}
摘自 朱金拖的專欄