jQuery and ASP.NET

January 3, 2009

Calculate Date and Time Difference Between Two Dates




A very common requirement is to display the Date and Time difference between two dates. Let us see how to do it:

C#


   DateTime date1 = 
   System.Convert.ToDateTime("2009-1-01 11:08:22");

   DateTime date2 = 
   System.Convert.ToDateTime("2009-1-02");

   TimeSpan ts = new TimeSpan();

   ts = date2.Subtract(date1);

   Response.Write(ts.Days + " Days " 
      + ts.Hours + " Hours " + 
      ts.Seconds + " Seconds ");        

 // Displays 0 Days 12 Hours 38 Seconds 


VB.NET


   Dim date1 As DateTime = _
    System.Convert.ToDateTime("2009-1-01 11:08:22")

   Dim date2 As DateTime = _
    System.Convert.ToDateTime("2009-1-02")

   Dim ts As New TimeSpan()

   ts = date2.Subtract(date1)

   Response.Write(ts.Days & " Days " & _
     ts.Hours & " Hours " & ts.Seconds & _
   " Seconds ")

 
 ' Displays 0 Days 12 Hours 38 Seconds 




The output displayed is : 0 Days 12 Hours 38 Seconds

If anyone has a requirement to do the same in SQL Server, check my post over here:

Find Hours, Minutes and Seconds in between two Datetime in SQL Server

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Calculate Date and Time Difference Between Two Dates"
  1. Hardeep said...
    April 22, 2009 12:35 AM

    Very Good Code
    Keep it up

  2. Anonymous said...
    May 11, 2009 10:19 AM

    not bad, but what if the requirement is to show the number of working days only (e.g. do not include Sat or Sun) ?

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions