Subscribe to Subscribers
Talk to Webmaster Tony John


Resources » .NET programming » .NET Framework

How to find difference between two Dates in C# or VB.NET ?


Posted Date:     Category: .NET Framework    
Author: Member Level: Bronze    Points: 10


It was an easy job with classic VB to find difference between 2 dates or times. Even though it is not very difficult, it is a tricky and confusing thing in C# and VB.NET. Learn how to find the difference between two Dates in C# or VB.NET?



 


Learn how to find difference between two Dates in C# or VB.NET?


Introduction
It was an easy job with classic VB to find difference between 2 dates or times. Even though it is not very difficult, it is a tricky and confusing thing in C# and VB.NET.

See the following sample code, which demonstrates how to calculate the difference between two DateTime objects using C# syntax.

DateTime startTime = DateTime.Now;

DateTime endTime = DateTime.Now.AddSeconds( 75 );

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );

In the above sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object.
Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.
Output:

Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0

In the above example, if you think the .Seconds property will return 75 (the difference between two times we are comparing is 75 seconds), that's a wrong assumption!! The Microsoft team has done it bit confusing. The .Seconds property will return 15 and the .Minutes property will return 1. So, you have to combine all these properties together to find the actual time difference. And unfortunately, you cannot get the Months and Years from the TimeSpan. The maximum you can get is the number of Days!

You can use the same above approach in VB.NET also, with the familiar VB syntax. But most of the VB guys prefer to use the old DateDiff function, which is very easy to use and also allows you to get the number of Months, years etc. It would have been very easier if the .NET team had provided a method equivalent to the classic VB DateDiff function.

There is an interesting discussion here, where Microsoft people are involved : http://blogs.msdn.com/vbfaq/archive/2004/05/30/144571.aspx





Did you like this resource? Share it with your friends and show your love!


Responses to "How to find difference between two Dates in C# or VB.NET ?"
Author: Ajesh Babu    04 Sep 2004Member Level: Silver   Points : 0
Hi
The portion about time differece is very good and it is simple.
Thanks



Author: Hristo Yankov    17 Aug 2005Member Level: Bronze   Points : 0
"In the above example, if you think the .Seconds property will return 75 (the difference between two times we are comparing is 75 seconds), that's a wrong assumption!! The Microsoft team has done it bit confusing. The .Seconds property will return 15 and the .Minutes property will return 1. So, you have to combine all these properties together to find the actual time difference."

Have you heard of the TotalMinutes propertie of the TimeSpan class?!



Author: Chetna    21 Sep 2006Member Level: Bronze   Points : 0
Thanks for code for time difference .for such a simple thing i was doing lot of coding..Net made it quite simple.
Thanks
again



Author: Miss Meetu Choudhary    25 Sep 2008Member Level: Gold   Points : 1
Hi The Topic Is Very Well Written and Good TO Understand.....
Really Useful Information........



--
I Would Love To Change The World But They Wont Give Me The Source Code

Spread D Smile n Never Say Bye

May Lord Shiva Bless All of US
Thanks and Regards
Meetu Choudhary
~~MEET~~



Author: arun    30 Nov 2008Member Level: Bronze   Points : 0
thanks for coding

Thanks
arun



Author: Fool To Code    02 Dec 2008Member Level: Gold   Points : 1
very nice code.

i think we can use DateDiff() function also to get difference between two dates.

but your code is great



Author: sangeetha    06 Mar 2009Member Level: Gold   Points : 1
DateTime sdate = Convert.ToDateTime(txtFromDate.Value);
DateTime edate = Convert.ToDateTime(txtToDate.Value);
TimeSpan ts = edate - sdate;
int days = ts.Days;



Author: Karl    17 May 2009Member Level: Bronze   Points : 0
Sangeetha -

Very nice! Works brilliantly.

Karl66



Author: Deepika Haridas    17 May 2009Member Level: Gold   Points : 1
Hi,

Very good article..
Useful for all..

Thanks for sharing..

Regards,
Deepika



Author: Prabhu    23 Nov 2009Member Level: Silver   Points : 1
In SQL, we can do this very easily....

select Hours = datediff(hh,0,DtDiff),
Minutes = datepart(minute,DtDiff),
Seconds = datepart(second,DtDiff) from
(select DtDiff = convert(datetime,'20090715 13:24:45.837')-convert(datetime,'20090213 02:44:37.923')) a

Hours Minutes Seconds
3658 40 7



Author: Sheir Ali    07 Jan 2010Member Level: Bronze   Points : 2
What about using the System.Data.Linq namespace and its SqlMethods.DateDiffMonth method?

For example, say...

DateTime starDT = {01-Jul-2009 12:00:00 AM}

DateTime endDT = {01-Nov-2009 12:00:00 AM}

then

int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(startDT, endDT);

==> 4

There are other DateDiff static methods in the SqlMethods class.




Author: Raja    15 Sep 2010Member Level: Silver   Points : 1
Dim NoOfHours As Integer = DateDiff(DateInterval.Hour, CDate(fi.CreationTime), CDate(DateTime.Now()))

Dim NoOfMinutes As Integer = DateDiff(DateInterval.Minute, CDate(fi.CreationTime), CDate(DateTime.Now()))



Author: Jason    21 Sep 2010Member Level: Bronze   Points : 1
Guys, you're all overworking the problem.

DateTime date_1 = DateTime.Now();
DateTime date_2 = DateTime.Now(); //or whatever other date
TimeSpan date_difference = date_1.Subtract(date_2);

//now, you have a date_difference object that has all sorts of goods.
var total_seconds = date_difference.TotalSeconds;
var total_days = date_difference.TotalDays;



Author: raj kumar sahu    13 Dec 2011Member Level: Silver   Points : 0
hi,

this method is simple and easy i like it

thanks



Guest Author: Mirec     22 Feb 2012
static void Main(string[] args)
{
DateTime date1;
DateTime date2;

date1 = new DateTime(2012, 02, 21, 8, 57, 11);
date2 = new DateTime(2012, 02, 22, 9, 20, 11);

TimeSpan timespan = date2.Subtract(date1);
Console.WriteLine("Difference - Days = " + timespan.Days);
Console.WriteLine("Difference - Hours = " + timespan.Hours);
Console.WriteLine("Difference - Minutes = " + timespan.Minutes);
Console.WriteLine("Difference - Seconds = " + timespan.Seconds);

Console.WriteLine("Difference Total - Days = " + timespan.TotalDays);
Console.WriteLine("Difference Total - Hours = " + timespan.TotalHours);
Console.WriteLine("Difference Total - Minutes = " + timespan.TotalMinutes);
Console.WriteLine("Difference Total - Seconds = " + timespan.TotalSeconds);

Console.ReadKey();

}



Guest Author: TimeSpan startTime=S     21 May 2012
TimeSpan startTime=System.DateTime.Now.TimeOfDay;


Guest Author: Mukesh Kumar     10 Jun 2012
Console.WriteLine("Enter your Date of Birth to Know your Current age in DD/MM/YY Format");
string str = Console.ReadLine();
DateTime dt1 = DateTime.Parse(str);
DateTime dt2 = DateTime.Parse("10/06/2012");
int result = (dt2 - dt1).Days;
result = result / 365;
Console.WriteLine("Your Current age is {0} years.",result);



Author: Bijit    20 Jun 2012Member Level: Gold   Points : 0
Hi Try this below code.



DateTime dt1 = Convert.ToDateTime("01/07/2011");
DateTime dt2 = Convert.ToDateTime("04/03/2012");
TimeSpan ts = dt1.Subtract(dt2);
int day = ts.Days;




Guest Author: T_joy     13 Jul 2012
how can i make this work in C?


Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: Parsing of XML data [DOM traversal]
    Previous Resource: How to find free disk space and total space of a disk drive
    Return to Resources
    Post New Resource
    Category: .NET Framework


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Panel  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.