-3

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

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

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

4

4 回答 4

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
于 2012-09-04T08:25:52.963 回答
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

于 2012-09-04T08:24:52.160 回答
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"));
}
于 2016-04-23T06:02:55.047 回答
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;
于 2012-09-04T08:51:59.170 回答