views:

453

answers:

6

Would appreciate it if anyone can help me figure out to substract 2 datetime fields to get the days left difference.

+1  A: 

You should look at TimeSpan.

Myles
+2  A: 

Use

TimeSpan

DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
rahul
+1  A: 
DateTime dt1 = new DateTime(2009,01,01,00,00,00);
DateTime dt2 = new DateTime(2009,12,31,23,59,59);

int days = (dt2 - dt1).Days;
Jesper Palm
A: 

Number of Days Difference

These answers take the number of days as an int from the System.TimeSpan structure that is the result of subtracting two System.DateTime fields...

Quick answer - gets the number of days difference.

        int numDaysDiff = date2.Subtract(date1).Days;

Alternate answer - uses Math.Abs to ensure it's not a negative number, just in case the dates might be supplied in either order.

        int numDaysDiff = Math.Abs( date2.Subtract(date1).Days );

Some sample data to finish it off using System namespace:

        // sample data
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddDays(10);

MSDN References (and more sample code ):

John K
+17  A: 

This is very easy to do with C#. For comparing DateTimes, we have a class called TimeSpan. The TimeSpan structure, in this case, would be defined as the difference between your two datetimes.

Let's say that your DateTimes are called start and end.

DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

We have established our DateTimes to June 14, 2009 and December 14, 2009.

Now, let's find the difference between the two. To do this, we create a TimeSpan:

TimeSpan difference = end - start;

With this TimeSpan object, you can express the difference in times in many different ways. However, you specifically asked for the difference in days, so here's how you can get that:

Console.WriteLine("Difference in days: " + difference.Days);

Thus, the property is called TimeSpan.Days.


Final Code

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.

For more information on using the TimeSpan structure, see this MSDN documentation (especially the C# examples).

Hope I helped!

UPDATE: Some answers have suggested taking doing subtraction in one step, such as with:

int days = (dt2 - dt1).Days;

or

int numDaysDiff = Math.Abs(date2.Subtract(date1).Days);

However, they are the same thing as in my answer, only shortened. This is because the DateTime.Subtract() method and the subtraction operator of DateTimes returns a TimeSpan, from which you can then access the amount of days. I have specifically used the longer approach in my code sample so that you clearly understand what is going on between your DateTime and TimeSpan objects and how it all works. Of course, the other approaches I just mentioned are fine, too.

UPDATE #2:

A very similar question was asked before, and it can be found here. However, the main point of that question was why the code sample (which is essentially equivalent to that of all the answers) sometimes provides an answer which is a day off. I think this is also important to this question.

As the main answer to the other question suggests, you can use this code:

int days = (int)Math.Ceiling(difference.TotalDays);

This code uses Math.Ceiling, which, according to MSDN, is:

Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

How Do You Want to Count the Days?

Thus, we now have an issue with how you want to count the days. Do you want to count part of a day (such as .5 of a day) as:

  • A full day - this would use Math.Ceiling to round up TimeSpan.TotalDays, so that you're counting started days.
  • Part of a day - you can just return the TimeSpan.TotalDays (not rounded) as a decimal (in the double datatype)
  • Nothing - you can ignore that part of a day and just return the TimeSpan.Days.

Here are code samples for the above:

Counting as a full day (using Math.Ceiling() to round up):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

int days = (int)Math.Ceiling(difference.TotalDays); //Extract days, counting parts of a day as a full day (rounding up).

Console.WriteLine("Difference in days: " + days); //Write to Console.

Counting as part of a day (NOT using Math.Ceiling(), instead leaving in decimal form as a part of a day):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

double days = difference.TotalDays; //Extract days, counting parts of a day as a part of a day (leaving in decimal form).

Console.WriteLine("Difference in days: " + days); //Write to Console.

Counting as nothing of a day (rounding down to the number of full days):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

int days = difference.TotalDays; //Extract days, counting parts of a day as nothing (rounding down).

Console.WriteLine("Difference in days: " + days); //Write to Console.
Maxim Zaslavsky
+2  A: 

The easiest way out is, making use of TimeSpan(). This Subtract function will return you the difference between two dates in terms of time span. Now you can fetch fields like days, months etc. To access days you can make use of Here is the sample code;

VB.Net code;

    Dim tsTimeSpan As TimeSpan
    Dim ldDate1 as Date
    Dim ldDate2 as Date
      'Initialize date variables here
       tsTimeSpan = ldDate1 .Subtract(ldDate2)
       Dim NumberOfDays as integer = tsTimeSpan.days

C#.Net code;

    DateTime lDate1;
    DateTime lDate2;
    TimeSpan tsTimeSpan ;
    int NumberOfDays;
      //Initialize date variables here
      tsTimeSpan = ldDate1 .Subtract(ldDate2);
      NumberOfDays = tsTimeSpan.days;
Vijay Balkawade
I believe he wants a C# code sample.
Maxim Zaslavsky
Please find C# code sample.
Vijay Balkawade