calculate number of months between two date

Posted on 2009-02-23
Last Modified: 2012-05-06
I am trying to calculate the number of months between two dates in c#.
I have two dates in a c# string.
At first i was calculating Mat.Abs(DateTime.Parse(txtStartDt.Value).Month - DateTime.Parse(txtEndDt.Value).Month))+ 1

Then i realized that i may have values where the years differ eg. 2007 - 2009 the code i have above doesnt account for that.  

What would be the best solution/algorithm to get the correct number of months from two dates?
Question by:joan2006
    LVL 92

    Assisted Solution

    by:Patrick Matthews
    The DateDiff function will return the number of month boundaries between 2 dates.

    If you are running it in SQL Server, the syntax is:

    SELECT DATEDIFF(month, @StartDate, @EndDate)

    No idea if C# has an analogous function.
    LVL 4

    Assisted Solution

    If you just need the value, there is a function called the DateDiff method.  Need to import the Microsoft.VisualBasic namespace, though, which is rather fat if you're going for a thin load.

    If you actually have to show the code to have it done, for a school project, or so, see the code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    namespace Console_DateTime
        class Program
            static void Main(string[] args)
                System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
                System.DateTime dtYestMidnight = new System.DateTime(2006, 9, 12, 0, 0, 0);
                System.TimeSpan diffResult = dtTodayNoon - dtYestMidnight;
                Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
                Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);

    Open in new window

    LVL 62

    Assisted Solution

    by:Fernando Soto
    Hi joan2006;

    I would suggest that you use the Visual Basic function to get the needed result. This function will take care of leap year and between to years. In order to use the Visual Basic function in a C# application you can do the following:

    1. Add a DLL reference Microsoft.VisualBasic to the application
       found in the .Net Table of the Add Reference dialog box.
    2. Add a using statement, using Microsoft.VisualBasic.
    3. Now you have access to the function. See code snippet.

    using Microsoft.VisualBasic;
    DateTime firstDate = DateTime.Parse("11/02/2008");
    DateTime secondDate = DateTime.Parse("02/14/2009");
    long noOfMonths = DateAndTime.DateDiff(DateInterval.Month, 
        firstDate, secondDate, FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);
    MessageBox.Show("Number of Months = " + noOfMonths.ToString());

    Open in new window

    LVL 62

    Expert Comment

    by:Fernando Soto
    Sorry type O in this line.

    1. Add a DLL reference Microsoft.VisualBasic to the application
       found in the .Net Tab of the Add Reference dialog box.
    LVL 68

    Accepted Solution

    You could also just do something like this:

    (txtEndDt.Yr * 12 + txtEndDt.Mth) - (txtStartDt.Yr * 12 + txtStartDt.Mth)

    Naturally you would have to convert the text to numeric (I'm not sure how to do that, but I'm guessing you know that already :-) ) .
    That's such a simple calc the overhead should be very low.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    Introduction In my previous article ( I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
    Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
    This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
    Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now