Get difference between two dates in C#


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.

The easy solution is to use the TimeSpan class and its members.

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 ");



Up Next
    Ebook Download
    View all
    Learn
    View all