How do I find difference between two dates?
By  Mahesh Chand August 05, 2005

This small article and code snippet shows how to get difference between two dates.

The attached code snippet shows how to get a difference between two dates.

The solution is easy but I have seen developers using different ways to find out difference between two dates by comparing the DateTime members. However, the .NET Framework class library provides TimeSpan class, which does the same.

DateTime.Subtract method returns a TimeSpan object, which has properties such as Days, Hours, Minutes and so on to get the difference in specific measurements.

Here is code snippet:

// Start date
DateTime startDate = new DateTime(2005, 2, 1, 3, 4, 12, 56);
// End date
DateTime endDate = new DateTime(2005, 12, 12, 4, 30, 45, 12
);

// Time span
TimeSpan diffDate = endDate.
Subtract ( startDate );

// Spit it out
Console.WriteLine( "Time Difference: "
);
Console
.WriteLine(diffDate.Days.ToString() + " Days"
);
Console
.WriteLine(diffDate.Hours.ToString() + " Hours"
);
Console
.WriteLine(diffDate.Minutes.ToString() + " Minutes"
);
Console
.WriteLine(diffDate.Seconds.ToString() + " Seconds "
);
Console
.WriteLine(diffDate.Milliseconds.ToString() + " Milliseconds ");