Date Diff in C# and Asp.net

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sajitk
    New Member
    • Feb 2008
    • 77

    Date Diff in C# and Asp.net

    Dear All

    I have two dates ile Start Date and End Date.

    I want to get the difference of the 2 dates in months.....How do we do it...

    For eg.

    Start Date = 01/11/2009
    End Date: 01/01/2010;

    The answer i want is 2 months

    Help requested.

    Thanks in advance

    Sajit
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    Convert both the dates to Datetime using
    Code:
    Convert.ToDateTime();
    use TimeSpan to calculate the difference. Then you can get the number of days by Days property of TimeSpan object.

    Comment

    • Curtis Rutland
      Recognized Expert Specialist
      • Apr 2008
      • 3264

      #3
      Code:
      DateTime dt1 = new DateTime(2009,10,19), 
          dt2 = new DateTime(2009,11,19);
      TimeSpan ts = dt2.Subtract(dt1);
      int months = ts.Days / 30;
      It isn't perfect, since not every month is 30 days, but it's close enough.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        Adapt InsertAlias's code to us ts.TotalDays
        TotalDays is the full timespan expressed as whole and fractional days

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          Good point, I used the wrong one.

          Comment

          Working...