st3lz
st3lz

Reputation: 39

Javascript difference in date using whole months

I've written this JavaScript function to calculate the difference in years and months from a date input, however the months are not calculating in a 'whole' form, meaning the difference should be exactly 1 month apart in days before the month count increments.

Currently, it calculates the difference between 2016-05-30 and 2016-06-02 as 1 month even though it is actually not equal to a month yet. I do not need to display days, however if this example is used I would like the output to be 0 months.

Please provide guidance. See function below.

$scope.calculateEmploymentPeriod = function(dateString){
        var today = new Date();
        var startDate = new Date($scope.data.client.date_appointed);
        var years_diff = today.getFullYear() - startDate.getFullYear();
        var m = today.getMonth() - startDate.getMonth();
        var months_count = (years_diff * 12) + m;

        if (m < 0 || (m == 0 && today.getDate() < startDate.getDate())) {
            years_diff--;
            months_count = months_count - (years_diff * 12); 
        }else if (months_count > 11){
            months_count = months_count - (years_diff * 12); 
        }else if (months_count == 11){
            months_count = months_count - (years_diff * 12); 
            years_diff--;
        }

        $scope.data.client.employment_duration_years = years_diff;
        $scope.data.client.employment_duration_months = months_count;
}

I would like to simply edit this version by adding another clause.

Upvotes: 0

Views: 56

Answers (2)

Gar
Gar

Reputation: 862

$scope.calculateEmploymentPeriod = function(dateString){
    var today = new Date();
    var startDate = new Date($scope.data.client.date_appointed);

    var years_diff = today.getFullYear() - startDate.getFullYear();

    var days_diff = today.getDate() - startDate.getDate()

    var months_count = today.getMonth() - startDate.getMonth();

      if (months_count<0) {months_count+=12;years_diff--}
      if (days_diff<0) months_count--;
      if (months_count<0) {months_count=0;}


    $scope.data.client.employment_duration_years = years_diff;
    $scope.data.client.employment_duration_months = months_count;
}

Upvotes: 1

Deepak Garg
Deepak Garg

Reputation: 142

try to put something like this..

else if(m==1 && today.getDate() < startDate.getDate()) {    
                months_count = months_count - (years_diff * 12) - 1;
            }

Upvotes: 1

Related Questions