TB.M
TB.M

Reputation: 363

AngularJS: Month filter in drop down list

Below I m looping for month but always feb month is missing;Please help with same.i want to display last 3 month show display.

$scope.months = [];
    var myDate = new Date();
    var previousMonth = new Date(myDate);

    for(var i=0;i<4;i++){
    var mon=myDate.getMonth()-i;
    if(mon<-1){
      mon=mon+12;
    }
    previousMonth.setMonth(mon);
    $scope.prevMonth = $filter('date')(previousMonth, 'MMMM');
    console.log("$scope.prevMonth ",$scope.prevMonth)
    $scope.prevYear = $filter('date')(previousMonth, 'yyyy');
    $scope.months.push({"val":previousMonth.getMonth()+1,"month":$scope.prevMonth});
    console.log($scope.months);
    $scope.years.push($scope.prevYear);

    }

Upvotes: 0

Views: 272

Answers (1)

Zohaib Jawaid
Zohaib Jawaid

Reputation: 143

Problem: That is because your day is 29 today and in February, max date is 28. when you try to set month as 1 (Feb) and date as 29 which is already set. It automatically increases the month ;)

For example:

var overMaxDate = new Date('2018-03-29');
    overMaxDate.setMonth(1)
    console.log(overMaxDate.toLocaleDateString());
    
var maxDate = new Date('2018-03-28');
    maxDate.setMonth(1)
    console.log(maxDate.toLocaleDateString());

Solution: You can use https://momentjs.com/ library to manipulate date any way you like. Or you can also keep track of days. Good luck!

Upvotes: 2

Related Questions