2012-09-04 211 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")); 
}