如何计算C#中两个给定日期之间的实际月差(日历年不近似)?

Jef*_*eff 7 .net c# datetime

示例:给定以下两个日期,结束始终大于或等于开始

start = 2001年1月1日

完成= 2002年3月15日

所以从2001年1月1日到2002年2月底

月= 12 + 2 = 14

2002年3月

15/30 = 0.5

所以总计是14.5个月的差异.

手工锻炼很容易,但我如何优雅地编码呢?目前我有很多if else和while循环的组合来实现我想要的但我相信有更简单的解决方案.

更新:输出需要精确(不是近似值),例如:如果从2001年1月1日开始到2001年4月16日结束,则输出应为1 + 1 + 1 = 3(1月,2月和3月)和16/31 = 0.516个月,所以总数是3.516.

另一个例子是如果我从2001年7月5日开始到2002年7月10日结束,产量应该是11个月到2002年6月底,并且(31-5)/ 31 = 0.839和10/31 = 0.323个月,所以总数是11 + 0.839 + 0.323 = 12.162.

我扩展了Josh Stodola的代码和Hightechrider的代码:

public static decimal GetMonthsInRange(this IDateRange thisDateRange)
{
    var start = thisDateRange.Start;
    var finish = thisDateRange.Finish;

    var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1;

    decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month);
    decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month);

    var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth;
    var daysApartInFinishMonth = finish.Day/daysInFinishMonth;

    return monthsApart + daysApartInStartMonth + daysApartInFinishMonth;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ola 10

int之前给出了答案,然后意识到你要求更准确的答案.我累了,所以我删除并上床睡觉.那么多,我无法入睡!出于某种原因,这个问题真的让我烦恼,我必须解决它.所以你去......

static void Main(string[] args)
{
    decimal diff;

    diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2002, 3, 15));
    Console.WriteLine(diff.ToString("n2")); //14.45

    diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2001, 4, 16));
    Console.WriteLine(diff.ToString("n2")); //3.50

    diff = monthDifference(new DateTime(2001, 7, 5), new DateTime(2002, 7, 10));
    Console.WriteLine(diff.ToString("n2")); //12.16

    Console.Read();
}

static decimal monthDifference(DateTime d1, DateTime d2)
{
    if (d1 > d2)
    {
        DateTime hold = d1;
        d1 = d2;
        d2 = hold;
    }

    int monthsApart = Math.Abs(12 * (d1.Year-d2.Year) + d1.Month - d2.Month) - 1;
    decimal daysInMonth1 = DateTime.DaysInMonth(d1.Year, d1.Month);
    decimal daysInMonth2 = DateTime.DaysInMonth(d2.Year, d2.Month);

    decimal dayPercentage = ((daysInMonth1 - d1.Day) / daysInMonth1)
                          + (d2.Day / daysInMonth2);
    return monthsApart + dayPercentage;
}
Run Code Online (Sandbox Code Playgroud)

现在我将有美好的梦想.晚安 :)