0

I am trying to calculate time in year months days in javascript

function getMonthsBetween (date1, date2)
{
    'use strict';
    // Months will be calculated between start and end dates.
    // Make sure start date is less than end date.
    // But remember if the difference should be negative.
    var start_date = date1;
    var end_date = date2;
    var inverse = false;

    if (date1 > date2)
    {
        start_date = date2;
        end_date = date1;
        inverse = true;
    }

    end_date = new Date(end_date); //If you don't do this, the original date passed will be changed. Dates are mutable objects.

    end_date.setDate(end_date.getDate() + 1);

    // Calculate the differences between the start and end dates
    var yearsDifference = end_date.getFullYear() - start_date.getFullYear();
    var monthsDifference = end_date.getMonth() - start_date.getMonth();
    var daysDifference = end_date.getDate() - start_date.getDate();

    var interval_month = yearsDifference +'-'+ monthsDifference +'-'+ daysDifference; 
    return interval_month;// Add fractional month
}

The issue is that when date is Passed like date1: 3-Apr-2017 and date2: 30-Apr-2017. It returns 27 Days, but infact these are 28 days from 3 to 30 April.

Any idea to calculate accurate days in year, months and days, i have spent two days on it already.

Ozan
  • 3,709
  • 2
  • 18
  • 23
Arshad Munir
  • 121
  • 2
  • 12
  • `28 days from 3 to 27 April`? I'm not following. – Dom Apr 03 '17 at 17:38
  • sorry for my bad, 28 days from 3 to 30 April. I dont know how to edit my Question. – Arshad Munir Apr 03 '17 at 17:43
  • All you have to do is parse the input into a `Date` object. Since `Date` is represented by a timestamp, it allows arithmetical operations (+, -, *, /, %). Here's the reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date when you got the proper period as `Date`, you can get months, years, etc. with `dateObj.getFullYear()`, `dateObj.getMonth()` etc. – Aloso Apr 03 '17 at 18:10

1 Answers1

1

See this example:

[https://jsfiddle.net/2ozuvn0L/2/]

In this example, you need pass start and end date.

getPeriod(new Date(2016, 3, 3), new Date(2017, 3, 30))

The answer: years 1, months 0, and days 27

Ederson
  • 49
  • 5