Resources » .NET programming » .NET Framework

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


Updated: Category: .NET Framework
Author: Member Level: BronzePoints: 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 2004   Member Level: Silver   Points : 0
Hi
The portion about time differece is very good and it is simple.
Thanks



Author: Hristo Yankov  17 Aug 2005   Member 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 2006   Member 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: Mrs. Meetu Choudhary Nanda  25 Sep 2008   Member 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 2008   Member Level: Bronze   Points : 0
thanks for coding

Thanks
arun



Author: Fool To Code  02 Dec 2008   Member 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 2009   Member 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 2009   Member Level: Bronze   Points : 0
Sangeetha -

Very nice! Works brilliantly.

Karl66



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

Very good article..
Useful for all..

Thanks for sharing..

Regards,
Deepika



Author: Prabhu  23 Nov 2009   Member 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 2010   Member 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 2010   Member 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 2010   Member 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 2011   Member 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: Aje   05 Apr 2012
Very useful and thank you...


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 2012   Member 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?


Guest Author: neha   24 Jun 2013
I am working on visual studio 10....actually making a window app...i want to
find d diff.(in days) b/w 2 dates....i use 2 dateTimePicker in a
Windows Form.....
DateTime d1=dateTimePicker1.Value;
String str1=(d1.Date).ToString();
DateTime d2 = dateTimePicker2.Value;
String str2 = (d2.Date).ToString();
if (str1== str2)
{ day.Text = "Same Dates";

}
else
{
TimeSpan t = dateTimePicker1.Value -
dateTimePicker2.Value;

int z = Math.Abs(t.Days)+1;
day.Text=z.ToString();
}




Author: Phagu Mahato  10 Oct 2013   Member Level: Gold   Points : 1
There are various ways for find difference between two Dates in C# or VB.NET . You can use DATEDIFF function to find the difference between a set of dates in Visual Basic.while use below line for C-Sharp
DateTime newDate = new DateTime(2013, 5, 1);
System.TimeSpan diff = secondDate.Subtract(firstDate);
String diff2 = (secondDate - firstDate).TotalDays.ToString();

Complete code for find difference between two dates in C#

sing System;
using System.Windows.Forms;

namespace Datedifference1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
System.DateTime fDate = new System.DateTime(2013, 10, 01);
System.DateTime sDate = new System.DateTime(2013,10,10);

System.TimeSpan diff = sDate.Subtract(fDate);
System.TimeSpan diff1 = sDate - fDate;

String diff2 = (sDate - fDate).TotalDays.ToString();

MessageBox.Show(diff1.ToString ());
}
}
}

Difference between two different dates using VB.NET for Minutes or Hours

Private Sub DateDiffExample()

Dim date11 As Date = New Date(2013, 5, 20, 10, 11, 2)
Dim date12 As Date = New Date(2013, 5, 20, 10, 12, 22)

Dim date13 As Long = DateDiff(DateInterval.Second, date11, date12)

End Sub


Private Sub DateDiffExample()

Dim date11 As Date = New Date(2013, 5, 21, 10, 11, 2)
Dim date12 As Date = New Date(2013, 5, 21, 10, 12, 20)

Dim date13 As Long = DateDiff(DateInterval.Minute, date11, date12)

End Sub
Underhere is another code snippet for date difference

DateTime startDate = new DateTime(2013, 2, 1, 3, 4, 12, 56);

DateTime endDate = new DateTime(2013, 12, 12, 4, 30, 45, 12);


TimeSpan diffDate = endDate.Subtract ( startDate );


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

Need for help in Date difference reply



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.


    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Awards & Gifts
    Talk to Webmaster Tony John
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India

    
    
    
    

    Click the "Follow" button above to follow Tony John