1439

How can one calculate the number of days between two dates in C#?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • The addition and subtraction operators are overloaded for the `DateTime` and `TimeSpan` types as you would expect. It's all pretty straightforward. -- What exact problem did you encounter? – BrainSlugs83 Sep 28 '18 at 21:23

17 Answers17

2570

Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays
Rohit
  • 1
  • 3
Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 713
    This answer is obviously correct, but you can also use `(a - b).Days` if you are interested in the total days as an `int` rather than a `double` with a decimal representation of the partial day difference. – PFranchise Dec 11 '12 at 15:27
  • 34
    this will return 1 less days, 08/31/2013-08/01/2013=31 but this is returning 30 only. – J R B Aug 07 '13 at 08:13
  • 76
    @JasRajBishnoi - you might want to check your maths. What is 31 - 1? – Greg Beech Aug 08 '13 at 18:36
  • 37
    JasRaj was also right in a sense that inclusive both dates it returns a day less in difference. It all depends upon the perspective. – Fahad Abid Janjua Sep 03 '13 at 06:52
  • 4
    @FahadAbidJanjua I came here looking for way to find difference between dates. To add: When talking about dates as whole days, the whole day would be considered for Aug 1. Therefore, it would be subtracted from the Aug 31, and leave only 30 days. It is incorrect to think otherwise. – Adam Cox Jun 20 '16 at 13:53
  • 39
    @FahadAbidJanjua It's not a matter or perspective but a matter of time, I mean, the time part of the date. 08/31/2013 - 08/01/2013 really means 08/31/2013 00:00:00 - 08/01/2013 00:00:00 which explains why it's 30 days, because the 08/31/2013 day is just starting. That also explains why, when querying on a DateTime property/field, the proper condition to get a range is "DateTimeProperty **>=** FromDate && DateTimeProperty **<** ToDate.AddDays(1)" – Miguel Veloso Jun 29 '16 at 14:33
  • 3
    To get totaldays difference including enddate, (int) (this.EndDate.GetValueOrDefault().AddDays(1).Date - this.StartDate.GetValueOrDefault().Date).TotalDays. In my case date variables are nullable. – Dhanuka777 Oct 20 '16 at 05:42
  • 11
    "Inclusive both dates" is not a matter of perspective, unless you truly believe that the difference between today and tomorrow is two days... – Stan Shaw Jan 26 '17 at 16:46
  • public static int DaysBetween(DateTime now , DateTime then) { var _now = now.Date; var _then= then.Date; return (int)(_now - _then).TotalDays; } – Fatih Mar 31 '17 at 12:13
  • Strange, if the year differs, when I run this code, it at max returns 365 days. Doesn't seem to work across years. Maybe it's just me? lol!?? – Barry Jun 29 '17 at 19:06
  • If you need to count day boundaries like SQL Server [`datediff`](https://learn.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql), this is not a suitable solution. – Frédéric Sep 26 '17 at 12:04
  • While I appreciate this solution I want to stress there are two ways to count days: 1. How many integers 24 hours has passed and 2.the more mundane way of counting how many midnights has passed. – jean Jan 29 '21 at 11:40
  • 1
    Assuming both are of `DateTime`, for my solution which only requires no of days, I used: `(EndDate.Date - StartDate.Date).Days` – Topman Aug 23 '22 at 00:39
  • I know this post is a bit old... but regarding the date difference debate, here is the other perspective. If your start date at work is Monday and your end date is Tuesday then you worked for two days, not one. And to calcualte you will use `.Date` – Peet Brits Sep 26 '22 at 12:03
375

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.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
Darren
  • 9,014
  • 2
  • 39
  • 50
  • 15
    The best answer because _"numbers of days"_ normally means whole days. It's worth noting that [`Days`](https://msdn.microsoft.com/en-us/library/system.datetime.day(v=vs.110).aspx) doesn't stop at 365 (as other properties like `Hours`, `Minutes`, `Second` which nax value is where the next higher property begins). Its the same as `TotalDays` but without fractions of a day and returning `int` instead of `double`. – Tim Schmelter Mar 14 '17 at 12:47
  • 1
    Will this always work as expected? For example, if one of the days being compared is a "spring ahead" Daylight Saving Time day, could the subtraction produce a TimeSpan of 23 hours, and if so, would the value of .Days on that 23-hour time span be 0? (I tried experimenting with this myself, but my results are inconclusive so far - https://stackoverflow.com/questions/43644252/why-doesnt-subtracting-two-local-datetime-values-appear-to-account-for-daylight) – Jon Schneider Apr 26 '17 at 21:17
  • Yup, this is what I needed - most valuable answer cmon now nobody wants to think about Minutes and Seconds in calculating days – solujic Jun 13 '17 at 12:28
  • if only 1,5 day has passed this .Days function will show only 1 Day? how i can alter it to show 2 days? i just have to always add + 1 day? – CDrosos Jun 05 '18 at 14:29
  • 4
    Upvoting this, because very often you would need "CALENDAR days between two dates", not just "number of 24-hour intervals". For example, you need to display an "X days ago" label in a timeline. In this case the difference between "Monday 11:59 pm" and "Tuesday 7:00 am" should be "1 day (ago)"... So the `.Date` part is really useful. Hope I'm making myself clear – Alex from Jitbit Jan 09 '19 at 23:33
  • I had a problem with my code where the difference in days between two days sometimes had some seconds difference and the rounding removed a day. This method solved the issue. – Gianmarco Biscini Sep 30 '22 at 05:52
161

Use TimeSpan object which is the result of date substraction:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
Vitaliy Liptchinsky
  • 5,221
  • 2
  • 18
  • 25
59

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;
pyrocumulus
  • 9,072
  • 2
  • 43
  • 53
37
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Philip Wallace
  • 7,905
  • 3
  • 28
  • 40
  • 1
    Anyway to get the days in between in DateTime format? Because I need each date to modify a certain field in tables :) Edit: Got it and posted it as answer below. Thanks – sys_debug Oct 30 '11 at 04:16
  • 4
    DateTime xmas = new DateTime(DateTime.Today.Year, 12, 25); would make it work on a year by year basis, not just 2009 :) –  Jul 12 '13 at 12:30
  • 1
    Subtract() is the OperatorOverload for DateTimes so its the same "(xmas - DateTime.Today).TotalDays - just longer. – Marc Aug 06 '14 at 08:41
30
// 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vijay Maheriya
  • 1,617
  • 16
  • 21
22

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

 (a.Date - b.Date).TotalDays
kingPuppy
  • 2,937
  • 1
  • 18
  • 18
  • 4
    This will always be a whole number though (i.e., n.00000) because the Date portion is always midnight. – JoeNCA Aug 28 '15 at 21:10
22

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
Ama
  • 1,373
  • 10
  • 24
11

You can try this

EndDate.Date.Subtract(DateTime.Now.Date).Days
Rohidas Kadam
  • 428
  • 5
  • 12
  • 2
    This actually helped me the best as my date difference was half a day but still when America is 1 day behind Australia I need to see there's actually one day difference. The other answers mentioned in this thread was showing either zero or some double number below 1 which I don't need. – Baz Guvenkaya Oct 19 '16 at 01:58
  • This is the best answer when the purpose is to check if the date has already passed to the next day, no matter if in terms of time is not a full 24h day. – oneberenjena Feb 05 '20 at 16:00
  • The best answer to exact difference without considering timestamp. – Sumit Shitole Feb 17 '23 at 04:36
4

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vijay Vj
  • 347
  • 3
  • 15
3

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pratyush Dhanuka
  • 1,405
  • 2
  • 11
  • 21
3

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! ^_^

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Curbside Coder
  • 291
  • 3
  • 15
  • Couldn't you just use "Days" instead of casting TotalDays? That conversion doesn't even round, it just truncates. if TotalDays is 1.99, your solution will give 1 (which may be what you want). – Michael Blackburn Feb 25 '21 at 17:14
0

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:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muba
  • 17
  • 1
0

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

int total_days = (EndDate - StartDate).TotalDays
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 29 '16 at 19:44
  • 3
    TotalDays returns a double: https://msdn.microsoft.com/en-us/library/system.timespan.totaldays(v=vs.110).aspx So you need a conversion to int – qnguyen Mar 15 '18 at 22:58
0

You can use the code below:

 int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Code_Worm
  • 4,069
  • 2
  • 30
  • 35
-4

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();
  • `DateTime.ParseExact` exists. You can specify the format without resorting to parsing it manually. This answer doesn't add anything that the existing answers don't already provide. – ProgrammingLlama Nov 25 '21 at 08:12
-27
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;
    }
}   
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 29
    This code is wrong in so many ways! 1) Lots of Winforms code not related to the question. 2) Wired way of showing message boxes using (I guess an WebBrowser control). 3) using a WebBrowser control to show a text that is shown in label already. 4) Using the OperatorOverload Subtract() (default for "-" operations) which is used for anyway if you do a "MyDateA - MyDateB". 5) No explanation tho this pile of code. – Marc Aug 06 '14 at 08:39