Calculate difference between two dates (number of days)?

C#Date

C# Problem Overview


I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?

C# Solutions


Solution 1 - C#

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

Solution 2 - C#

The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:

(EndDate.Date - StartDate.Date).Days

Again assuming StartDate and EndDate are of type DateTime.

Solution 3 - C#

Use TimeSpan object which is the result of date substraction:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;

Solution 4 - C#

I think this will do what you want:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);

TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;

Solution 5 - C#

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;

Solution 6 - C#

// Difference in days, hours, and minutes.

TimeSpan ts = EndDate - StartDate;

// Difference in days.

int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double

// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double

// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double

You can also get the difference in seconds, milliseconds and ticks.

Solution 7 - C#

In case someone wants numer of whole days as a double (a, b of type DateTime):

 (a.Date - b.Date).TotalDays

Solution 8 - C#

There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.

Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.

  • If you want the duration in days to include fractions of days, then as already suggested use (EndDate - StartDate).TotalDays.
  • If you want the duration to reflect the distance between two days, then use (EndDate.Date - StartDate.Date).Days
  • If you want the duration to reflect the duration between the morning of the start date, and the evening of the end date (what you typically see in project management software), then use (EndDate.Date - StartDate.Date).Days + 1

Solution 9 - C#

You can try this

EndDate.Date.Subtract(DateTime.Now.Date).Days

Solution 10 - C#

Using a timespan would solve the problems as it has many attributes:

DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();

Solution 11 - C#

For a and b as two DateTime types:

DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();

Solution 12 - C#

For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:

int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);

This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).

If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.

On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.

Happy coding! ^_^

Solution 13 - C#

First declare a class that will return later:

public void date()
{
    Datetime startdate;
    Datetime enddate;
    Timespan remaindate;

    startdate = DateTime.Parse(txtstartdate.Text).Date;
    enddate = DateTime.Parse(txtenddate.Text).Date;

    remaindate = enddate - startdate;

    if (remaindate != null)
    {
        lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
    }
    else
    {
        lblmsg.Text = "correct your code again.";
    }
}

protected void btncal_Click(object sender, EventArgs e)
{
    date();
}

Use a button control to call the above class. Here is an example:

Solution 14 - C#

Get the difference between the two dates and then get the days from:

int total_days = (EndDate - StartDate).TotalDays

Solution 15 - C#

You can use the code below:

 int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds

Solution 16 - C#

try this truly worked Get actual days diff. date format is "dd/MM/yyyy"

  string[] d1 = txtFromDate.Values.Split('/');
  string[] d2 = txtToDate.Values.Split('/');

  DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
  DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));

  TimeSpan TDiff = ToDt.Subtract(FrmDt);
  String DaysDiff = TDiff.TotalDays.ToString();

Solution 17 - C#

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Greg BeechView Answer on Stackoverflow
Solution 2 - C#DarrenView Answer on Stackoverflow
Solution 3 - C#Vitaliy LiptchinskyView Answer on Stackoverflow
Solution 4 - C#pyrocumulusView Answer on Stackoverflow
Solution 5 - C#Philip WallaceView Answer on Stackoverflow
Solution 6 - C#Vijay MaheriyaView Answer on Stackoverflow
Solution 7 - C#kingPuppyView Answer on Stackoverflow
Solution 8 - C#AmaView Answer on Stackoverflow
Solution 9 - C#Rohidas KadamView Answer on Stackoverflow
Solution 10 - C#Vijay VjView Answer on Stackoverflow
Solution 11 - C#Pratyush DhanukaView Answer on Stackoverflow
Solution 12 - C#Curbside CoderView Answer on Stackoverflow
Solution 13 - C#MubaView Answer on Stackoverflow
Solution 14 - C#Muhamad EissaView Answer on Stackoverflow
Solution 15 - C#Code_WormView Answer on Stackoverflow
Solution 16 - C#Sagar JadhavView Answer on Stackoverflow
Solution 17 - C#sangeethaView Answer on Stackoverflow