Difference in months between two dates

前端 未结 30 1187
天命终不由人
天命终不由人 2020-11-22 11:02

How to calculate the difference in months between two dates in C#?

Is there is equivalent of VB\'s DateDiff() method in C#. I need to find difference in

30条回答
  •  伪装坚强ぢ
    2020-11-22 11:42

    I wrote a function to accomplish this, because the others ways weren't working for me.

    public string getEndDate (DateTime startDate,decimal monthCount)
    {
        int y = startDate.Year;
        int m = startDate.Month;
    
        for (decimal  i = monthCount; i > 1; i--)
        {
            m++;
            if (m == 12)
            { y++;
                m = 1;
            }
        }
        return string.Format("{0}-{1}-{2}", y.ToString(), m.ToString(), startDate.Day.ToString());
    }
    

提交回复
热议问题