/ Published in: C#
Datetime difference in years, months and days, corrected version of existing snippet called DateTime Difference provided by hnielsen
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
class DateTimeDiff { /// <summary> /// Difference btweeen dates expressed in years, months and days. /// </summary> /// <param name="dtStartDate"></param> /// <param name="dtEndDate"></param> /// <param name="YearsDiff"></param> /// <param name="MonthsDiff"></param> /// <param name="DaysDiff"></param> public static void TimeSpanToDate( DateTime dtStartDate, DateTime dtEndDate, out Int32 YearsDiff, out Int32 MonthsDiff, out Int32 DaysDiff ) { bool bRegularOrder = true; // is the start date before end date if (dtEndDate < dtStartDate) { // if the order of dates is reversed, dates are reversed, then difference is computed // however, we remember that order is reversed, so at the end we put minus before all results componenet DateTime d3 = dtStartDate; dtStartDate = dtEndDate; dtEndDate = d3; bRegularOrder = false; } // compute difference in total months MonthsDiff = 12 * (dtEndDate.Year - dtStartDate.Year) + (dtEndDate.Month - dtStartDate.Month); // based upon the days // adjust months & compute actual days difference if (dtEndDate.Day < dtStartDate.Day) { // check if both dates are the last day in the month if (dtStartDate.Day == DateTime.DaysInMonth(dtStartDate.Year, dtStartDate.Month) && dtEndDate.Day == DateTime.DaysInMonth(dtEndDate.Year, dtEndDate.Month)) { DaysDiff = 0; // whereas month number remains unchanged } else { MonthsDiff--; Int32 iBrojDanaPrethodnogMesecaZavrsnogDatuma = DayInMonthOfPreviousMonth(dtEndDate); DaysDiff = Math.Max(0, iBrojDanaPrethodnogMesecaZavrsnogDatuma - dtStartDate.Day) + dtEndDate.Day; } } else { DaysDiff = dtEndDate.Day - dtStartDate.Day; } // compute YearsDiff & actual MonthsDiff YearsDiff = MonthsDiff / 12; MonthsDiff -= YearsDiff * 12; // if the order was reversed, put minus sign before all componenet results if (!bRegularOrder) { YearsDiff = -YearsDiff; MonthsDiff = -MonthsDiff; DaysDiff = -DaysDiff; } } private static Int32 DayInMonthOfPreviousMonth(DateTime dt) { Int32 month = dt.Month; Int32 year = dt.Year; // previous month month--; if (month == 0) { month = 12; year--; } return DateTime.DaysInMonth(year, month); } }