How do I find difference between two dates?

How do I find difference between two dates?

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

From:
http://www.c-sharpcorner.com/UploadFile/mahesh/TwoDatesDifference08052005152233PM/TwoDatesDifference.aspx?ArticleID=7e45df46-b52a-4b48-b987-2d53201234a6

posted @ 2005-11-29 15:29  jhtchina  阅读(419)  评论(0编辑  收藏  举报