2012-09-04 212 views
-3

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

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

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

+0

“你尝试过什么”? –

+6

由于月份长度不同,所以月份的分数是没有意义的。 – Rawling

+1

没有“月份长度”的定义没有答案。 –

回答

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 
+0

如果我可能会问为什么365.25? – johnnie

+0

@johnnie因为每4年有一个额外的天 – LaGrandMere

+1

@johnnie在天文学中,Julian年是一个时间单位,定义为365.25天,每个86400 SI秒(没有闰秒)。它提供了更多的精度。如果你没有使用.25,结果将是16,而不是15.83 ... – Jensen

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你多远当月推进,substracts结束日期 - 的startDate

+0

注意你可以在取消时放下'-1'。 – Rawling

+0

@完全正确的,我直接写了它,我怎么计算它,但2 -1可以被删除:) – LaGrandMere

0

这将适用于您。 但您需要15.87个月的确切答案,您必须单独维护月的天数enum 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; 
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")); 
}