Months Difference

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bootzwiz
    New Member
    • Jan 2007
    • 14

    #1

    Months Difference

    How can we find months difference between two dates.

    For Exp :

    Start Date : 05/03/2007
    End Date : 06/10/2007

    How to calucate months difference for any dates?.
  • vituko
    New Member
    • Dec 2006
    • 48

    #2
    [CODE=javascript]
    var a = new Date (2000, 1, 1) ;
    var b = new Date (2002, 5, 1) ;
    alert (12 * (b.getYear() - a.getYear()) + b.getMonth() - a.getMonth()) ;
    [/CODE]
    Last edited by gits; Jul 27 '07, 11:11 AM. Reason: added CODE tags

    Comment

    • weedweaver
      New Member
      • Jul 2007
      • 2

      #3
      Code:
      private int CalculateMonthDifference(DateTime startDate, DateTime endDate)
      		{
      			int diff = 0;
      
      			while(startDate <= endDate)
      			{
      				endDate = endDate.AddMonths(-1);
      				diff++;
      			}
      			if (diff == 0)
      			{
      				return diff;
      			}
      			else
      			{
      				return diff -1;
      			}
      		}
      This will loop through and give the number of months difference by subtracting 1 month from the end date until it less than the start date. Ok its not elegent but it works and the number of loops is not massive (e.g. 10 years diff would be 1200 loops which on todays machines is nothing)
      Last edited by gits; Jul 27 '07, 11:11 AM. Reason: added CODE tags

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        Originally posted by weedweaver
        Code:
        private int CalculateMonthDifference(DateTime startDate, DateTime endDate)
        		{
        			int diff = 0;
        
        			while(startDate <= endDate)
        			{
        				endDate = endDate.AddMonths(-1);
        				diff++;
        			}
        			if (diff == 0)
        			{
        				return diff;
        			}
        			else
        			{
        				return diff -1;
        			}
        		}
        This will loop through and give the number of months difference by subtracting 1 month from the end date until it less than the start date. Ok its not elegent but it works and the number of loops is not massive (e.g. 10 years diff would be 1200 loops which on todays machines is nothing)
        hi ...

        unfortunatly this is not a javascript solution to the problem?

        kind regards

        Comment

        Working...