How do I calculate the number of days between two dates in C#?


Does anyone have a code sample that might help


Answer this question

How do I calculate the number of days between two dates in C#?

  • kkarre

    This code was very helpful! I've always reverted back to the Delphi TDateTime class to do my date calculations, but now that I know about TimeSpan I can do it all in C#.NET. Thanks!
  • Rui Dias VD

    Yup, your right. That was fast!  I've actually gone ahead and marked your post as the correct answer.  To keep the FAQ clean I'll eventually delete my first reply that was posted as part of a forum demo I was recording. 

    There are also a couple of other obvious bugs in the code that I posted. :-)

  • yaasiva

    Here's one way:
    DateTime now = DateTime.Now;
    DateTime then = new DateTime (1, 1, 2005);
    TimeSpan diff = now - then;
    int days = diff.Days;

  • prk


    Here is one way to accomplish this...


     private int daysPast(DateTime oldDate)
     {
     
      long tickDiff = DateTime.Now.Ticks - oldDate.Ticks;
      tickDiff = tickDiff / 10000000; //have seconds now
      _age = (int)(tickDiff / 86400);
      return _age;//should be days
     }



  • yanivpinhas

    Dear Josh,
    This can be easily accomplished using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the max. and min. values for the DateTime Type and show it in a Console window, then I may write something like:

    DateTime d1=DateTime.MinValue;
    DateTime d2=DateTime.MaxValue;
    TimeSpan span=d2-d1;
    Console.WriteLine
             ( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );

    Note that I used the TotalDays property to get the number of days in between. This gets me the number of days putting in consideration the years with fraction days (years with 366 days). I could also use the property "Days" that would get me the value considering that all the years consist of 365 days only.

    Hope this could be helpful,
    Regards,

  • Michelle A.

    Here's also a suggestion:

    Code Snippet

    private int DateDiffInDays(DateTime fromDate, DateTime toDate)

    {

    return toDate.Subtract(fromDate).Days;

    }



  • hendrik swanepoel

    Another way, using only DateTime:



    private int GetDaysBetweenDates(DateTime firstDate, DateTime secondDate)
    {
       return secondDate.Subtract(firstDate).Days;
    }

     
    PS: The code tags put all my code on one line, not me! Smile

    One bug in your original code is that the name _age does not exist.  The fix:

    int _age = (int)(tickDiff/86400);
     


    Another one is that you assume all days are 86400 seconds long. But there is one day that has 82800 seconds and another that has 90000 (for daylight savings).  This could introduce a bug.



  • How do I calculate the number of days between two dates in C#?