获取两个时间段之间的月份

/// <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个月,如果大于,跳出
                    break;
                filed += c1.ToString("yyyy-MM") + "|";
                c1 = c1.AddMonths(1);
            }
            return filed.TrimEnd('|');
        }
        catch { return null; }
    }

 

你可能感兴趣的:(c,String,null)