Calculating absolute difference between two dates
Recently, While working on an application, I came across a need of showing absolute diffrence between two dates. i.e. If I have two dates 01/01/2010 12:00 and 25/12/2010 18:00 then my date diffrence should be shown as 2 yrs 11 months 23 days 22 hrs 58 mins upto the last second. Such kind of date diffrence is often seen in video sharing website like youtube.com. So, I search for .net code which will give me such date diffrence. When I didn’t got any, I decided to code my own function.
My code for deriving date diffrence in such format is as follows:
public static string GetDateDiff(DateTime startDate, DateTime endDate)
{
string timeStr = string.Empty;
int year = 0;
int month = 0;
int days = 0;
int hours = 0;
int mins = 0;
int sec = 0;
TimeSpan ts = new TimeSpan();
ts = endDate.Subtract(startDate);
year = (ts.Days / 365);
do
{
for (int i = 0; i <= 12; i++)
{
if (endDate.Subtract(startDate.AddYears(year).AddMonths(i)).Days > 0)
{
month = i;
}
else
{
break;
}
}
if (month > 12)
year = year + 1;
} while (month > 12);
DateTime Newdt = startDate.AddYears(year).AddMonths(month);
days = endDate.Subtract(Newdt).Days;
hours = endDate.Subtract(Newdt.AddDays(days)).Hours;
mins = endDate.Subtract(Newdt.AddDays(days).AddHours(hours)).Minutes;
sec = endDate.Subtract(Newdt.AddDays(days).AddHours(hours).AddMinutes(mins)).Seconds;
if (year > 0)
timeStr += year.ToString() + " yrs ";
if (month > 0)
timeStr += month.ToString() + " months ";
if (days > 0)
timeStr += days.ToString() + " days ";
if (hours > 0)
timeStr += hours.ToString() + " hrs ";
if (mins > 0)
timeStr += mins.ToString() + " mins ";
if (sec > 0)
timeStr += sec.ToString() + " sec ";
return (timeStr);
}
This function takes two dates as input paramters and then calculates the diffrence between these two dates upto the last second. If time is not passed in date format, then hours, minutes and seconds will not be included in the result.
To demonstrate the use of this function, I have use the below code.
DateTime result = Convert.ToDateTime(input.ToString());
Console.WriteLine("Date Diffrence is : " + GetDateDiff(result, DateTime.Now));
result = Convert.ToDateTime(input.ToString());
Console.WriteLine("Date Diffrence since 1st January 2010 is : " + GetDateDiff(new DateTime(2010, 1, 1),result));
Console.WriteLine("Absolute Date Diffrence since 1st January 2012 is : " + GetDateDiff(new DateTime(2010, 1, 1,1,1,1), result));
I take one input parameter and then calculates the diffrence between input date and Datetime.Now, input date and 1st January 2010, input date and 1st January 2012
Below is the output when my input is 12/25/2012
Since hours, minutes and seconds were passed as input in the last case, the output included the time diffrence in addition to the date diffrence..Modify the code as per your requirement.
Attached is the sample code..Download and test..