Here you can find a method that can calculate the years, months and days between 2 dates.
public static void DateDifference(DateTime startDate, DateTime endDate, out int years, out int months, out int days)
{
years = endDate.Year - startDate.Year;
months = endDate.Month - startDate.Month;
days = endDate.Day - startDate.Day;
if (days < 0) months -= 1;
while (months < 0) { months += 12; years -= 1; }
TimeSpan timeSpan = endDate - startDate.AddYears(years).AddMonths(months);
days = (int)Math.Round(timeSpan.TotalDays);
}
And here is a method that uses the previous method and returns a string representation of the difference:
public static string DateDifference(DateTime startDate, DateTime endDate)
{
int years, months, days;
DateDifference(startDate, endDate, out years, out months, out days);
return
((years != 0 ? years.ToString() + "y " : "") +
(months != 0 ? months.ToString() + "m " : "") +
(days != 0 ? days.ToString() + "d" : "")).TrimEnd();
}
4 comments:
Watch out! If startDate and endDate are not in UTC, this can return invalid results. For example, one date may be in daylight saving, while the other isn't. Their difference will miss or have one extra hour.
Good point. I hadn't thought about that situation, because I thought it was logical that if you compare DateTimes, they should both use the same timezone, or be UTC.
One of us must be smoking..something that I don't know what it is. Try your code with Ending Date 3/1/2006 and 7/31/2002 as starting date.
Anonymous, I just tried your example and I see nothing wrong.
I get 3 years, 7 months and 1 day.
If I call startDate.AddYears(3).AddMonths(7).AddDays(1), I get the right end date (March 1st 2006).
I used this code snippet:
DateTime start = new DateTime(2002, 7, 31);
DateTime end = new DateTime(2006, 3, 1);
int years, months, days;
DateDifference(start, end, out years, out months, out days);
Console.WriteLine("{0}y {1}m {2}d", years, months, days);
DateTime newEnd = start.AddYears(years).AddMonths(months).AddDays(days);
Console.WriteLine(newEnd);
Post a Comment