2011-11-15 146 views
1

我需要能夠減去2個日期並獲得2和2之間的年份和月份。有沒有人知道有任何簡單的方法來做到這一點?減去2日期

我看過TimeSpan返回時減去日期,但沒有'NumberOfYears'等選項!

編輯:

我發現下面的文章

http://www.codeproject.com/KB/datetime/TimePeriod.aspx?msg=4078849#xx4078849xx

這是真棒!

+1

」用於測量持續時間的最大時間單位是一天。時間間隔是以天爲單位測量的一致性,因爲大單位時間(如月和年)中的天數有所不同。「 MSDN – RvdK

+1

可能重複[如何顯示兩個日期之間的差異爲00Y 00M](http://stackoverflow.com/questions/771642/how-to-display-difference-between-two-dates-as-00y-00m) –

+3

1月31日到3月1日有幾個月? – Gabe

回答

3

你可以脫下蜱以來的時間開始(也沒有時間的開始,但01/01/0001):

// Assuming date 1 is the later date 
DateTime newDate = new DateTime(myDate1.Ticks - myDate2.Ticks); 

// NOTE : you might need to take 1 off each property, as they start at 1 
string.Format("{0} Years, {1} Months, {2} Days", newDate.Year, newDate.Month, newDate.Day); 

您可以創建一個模塊那將爲你做你的工作,這將循環計算日期之間的年數,直到年份相等,或者在較早的月份更大的情況下年份減少一年。然後你就可以循環下去,直到幾個月都沒有忘記,從12下降到1

int yearCount = 0; 
int monthCount = 0; 
int earliestYear = 0; 
int earliestMonth = 0; 
int latestYear = 0; 
int latestMonth = 0; 

// Get the earlier date, assuming that you haven't calculated which date is the latter already. 
if (myDate1 > myDate2) 
{ 
    earliestYear = myDate2.Year; 
    earliestMonth = myDate2.Month; 
} 
else 
{ 
    latestYear = myDate1.Year; 
    latestMonth = myDate1.Month; 
} 

// Get the years between (remember not to include a year where the earlier dates month is greater than the latter. E.g. 09/2011 -> 01/2013 will only be 1 year, not 2! 
while(earliestYear < latestYear && (earliestMonth <= latestMonth || earliestYear < (latestYear - 1))) 
{ 
    yearCount++; 
    earliestYear++; 
} 

// Finally get the months between, moving back to january after december. 
while (earliestMonth != latestMonth) 
{ 
    monthCount++; 

    if (earliestMonth == 12) 
    { 
     earliestMonth = 1; 
    } 
    else 
    { 
     earliestMonth++; 
    } 
} 

string.Format("{0} years and {1} months", yearCount, monthCount); 

這是寫在飛行中未測試的代碼給你一個粗略的想法相同。

這還假定你將代表是有兩個日期,如29/02/1988和1988年1月3日(英國日期時間格式)

之間1個月

你可以嘗試使用時間跨度來完成任務,沒有辦法得到幾年沒有一些手動代碼,雖然我相信你可以把那部分弄清楚:-)(例如類似於days/365.25的東西)

+0

我在TimeSpan上看不到「年份」屬性:http://msdn.microsoft.com/en-us/library/system.timespan.aspx – RvdK

+0

-1:在什麼框架中使用Timespan對象有'年'屬性? –

+1

我沒有強調,有一個年份的財產,但請糾正我,我做了什麼。 – ThePower

0

爲什麼不創建DateTime擴展方法返回一個Tuple<int, int>或自定義類來滿足您的需求?特別是作爲TimeSpan不會滿足您的需求很好,因爲你必須從天來計算月和年(並採取每個月的長度考慮在內。)

public static Tuple<int, int> GetYearsAndMonthsDifference(this DateTime dt1, DateTime dt2) 
{ 
    DateTime laterDate; 
    DateTime earlierDate; 

    if (dt1 > dt2) 
    { 
     earlierDate = dt2; 
     laterDate = dt1; 
    } 
    else 
    { 
     earlierDate = dt1; 
     laterDate = dt2; 
    } 

    int months = 0; 

    while(earlierDate.Month != laterDate.Month || earlierDate.Year != laterDate.Year) 
    { 
     months++; 
     earlierDate = earlierDate.AddMonths(1); 
    } 

    return Tuple.Create<int, int>(months/12, months % 12); 
} 

用法:

var dt1 = DateTime.Now; 
var dt2 = new DateTime(2010, 1, 1); 

var difference = dt1.GetYearsAndMonthsDifference(dt2); 

Console.WriteLine(string.Format("Years: {0}", difference.Item1)); 
Console.WriteLine(string.Format("Months: {0}", difference.Item2)); 

N.B:如果你不喜歡Item1Item2那麼你總是可以創建一個更好的自定義結構/類並返回它,而不是Tuple<int, int>

+0

會發生什麼當dt1.Month == 11和dt2.Month == 1但dt1.Year == 2012和dt2.Year == 2011?通過這個屬性的結果將是1年10個月(這是離開)。 –

+0

2011年12月和2012年1月之間的差異是否可行? – ThePower

+0

@ThePower確實,現在修好了。月份:1,年份:0 –

0

您可以使用tick中的diff創建DateTime。

DateTime tmp = new DateTime(date1.Ticks - date2.Ticks); 
Console.WriteLine(tmp.Year - 1); 
Console.WriteLine(tmp.Month - 1); 
Console.WriteLine(tmp.Day - 1); 

你必須從一切減去1,因爲1/1/1是第一個可能的日期,而不是0/0/0

+0

我找到了。 2日期,差別是65yrs,使用這種方法我得到66yrs 1個月。我實際使用: http://www.codeproject.com/KB/datetime/TimePeriod.aspx?msg=4078849#xx4078849xx –