SIGN UP MEMBER LOGIN:    
ARTICLE

Get difference between two dates in C#

Posted by Mahesh Chand Articles | How do I August 05, 2005
This code snippet shows how to get difference between two dates in C#.
Reader Level:


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



Login to add your contents and source code to this article
Article Extensions
Contents added by Mahesh Chand on Jan 28, 2011
share this article :
post comment
 

Ok I have just published a detailed DateTime tutorial. Here is the URL: http://www.c-sharpcorner.com/UploadFile/mahesh/5242/Default.aspx

Posted by Mahesh Chand Jan 28, 2011

hi mahesh this is goo one....but i am doing one lodge application i want to store date &  time in DB SQL server 2005 & take a diffrence can u help me?  

Posted by om dudhagundi Oct 03, 2010

it worked!

Posted by omkar dongre Jan 06, 2010

Not sure what you mean. Why dont you post your question on forums by clicking on the Forums link at the top.

Posted by Mahesh Chand Apr 06, 2009

I wonder how the code, countdown the shown date time.

Posted by asil Dec 25, 2008
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor