两个日期之间的月份差异

时间:2012-09-04 08:15:35

标签: c# datetime

大家好我需要得到两个日期之间的区别,作为小数。

示例:2010年2月13日至2011年6月10日之间的差异为15.87个月。

我将如何在c#中完成此操作?

4 个答案:

答案 0 :(得分:5)

如果您想要近似值,可以执行以下操作:

var first = new DateTime(2010, 2, 13);
var second = new DateTime(2011, 6, 10);
var result = second.Subtract(first).Days / (365.25 / 12);

Console.Write(result);

结果将是:

15,8357289527721

答案 1 :(得分:2)

   public static int diffMonths(this DateTime startDate, DateTime endDate)
    {
            return (startDate.Year * 12 + startDate.Month + startDate.Day/System.DateTime.DaysInMonth(startDate.Year, startDate.Month))
                    - (endDate.Year * 12 + endDate.Month + endDate.Day/System.DateTime.DaysInMonth(endDate.Year, endDate.Month));
    }

它使用DaysInMonth计算您当月的进度,并减去endDate - startDate

答案 2 :(得分:1)

试试这个:

string fmt = "yyyy-MM-dd";
DateTime first = DateTime.Today;

for (int i = 0; i < 45; i++)
{
    DateTime second = first.AddMonths(3).AddDays(i);


    int wholeMonths = ((second.Year - first.Year) * 12) + second.Month - first.Month;
    DateTime firstPlusWholeMonths = first.AddMonths(wholeMonths);

    double fractMonths;
    if (firstPlusWholeMonths == second) fractMonths = wholeMonths;
    else
    {
        double diff = second.Subtract(firstPlusWholeMonths).TotalDays;
        fractMonths = wholeMonths + (diff * 12 / 365.25);
    }

    Console.WriteLine("From {0} to {1} is {2} months.", first.ToString(fmt), second.ToString(fmt), fractMonths.ToString("0.00000000"));
}

答案 3 :(得分:0)

这对你有用。 但是你需要确切的答案15.87个月你必须单独维护月份的枚举天数            DateTime dt1 = new DateTime(2010,02,13);            DateTime dt2 = new DateTime(2011,06,10);

       TimeSpan ts = dt2.Subtract(dt1);
       double days = (double)ts.TotalHours / (24);
       double months = days / 30.4;