.net中简单获取两个日期相差的月份数

private void  getMonths(string  dt1, string dt2)
        {
            dt1 = dt1 + "-01";
            dt2 = dt2 + "-01";
           

            DateTime dt3 = Convert.ToDateTime(dt1);
            DateTime dt4 = Convert.ToDateTime(dt2);

            for(int i=0;i<((dt4.Year * 12 + dt4.Month) - (dt3.Year * 12 + dt3.Month));i++)//获取相差的月份数并循环
            {
                Response.Write(dt3.AddMonths(i+1).ToString("yyyy-MM")+"<br/>");//打印出2008-08的格式一直到2009-02
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            this.getMonths("2008-08","2009-02");//调用方法
        }

你可能感兴趣的:(.net)