cyberoy
cyberoy

Reputation: 373

How can I start from current date in Date Picker using Javascript AngularJS

in my date picker month is starting from current month to next 12 months. Dates are showing from first date to last date. But I want to show current date to last date of current month. Past dates should not be shown. I think we can set a limit a, like i=dates.getDate() to start from current date. Not sure. Please check my fiddle and code.

datepicker = angular.module('datepicker', []);

datepicker.controller('dateTimePicker', ['$scope', function($scope){
	console.log('alive');
        
  var date = new Date();
  var months = [],
    monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
  for (var i = 0; i <= 12; i++) {
    months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
    date.setMonth(date.getMonth() + 1);
  }
  $scope.year =2015;

  $scope.changeMonth = function(steps) {
    if ($scope.monthIndex + steps >= 0 &&
      $scope.monthIndex + steps <= 12
    ) {
      $scope.dateValues = [];
      $scope.monthIndex = $scope.monthIndex + steps;
      $scope.monthName = $scope.months[$scope.monthIndex];
       var date = new Date();
        console.log(date.getMonth());
        var offset = date.getMonth()
       console.log($scope.monthIndex);
        var offsetDate = offset + $scope.monthIndex;
      $scope.nDays = new Date( $scope.year,  offsetDate+1, 0).getDate();
        console.log(offsetDate+1);
        console.log(new Date( $scope.year, offsetDate, 1));
      for (i = 1; i <= $scope.nDays; i++) {  
    	var d = new Date();
    	$scope.dateValues.push(new Date($scope.year,  offsetDate, i));
  	  }
      
    }else{console.log("missed")}
  };

  $scope.monthIndex = 0;
  $scope.months = months;
  $scope.monthName = months[0];
  $scope.changeMonth(0);

}]);

fiddle link :- https://jsfiddle.net/enkode/89sbv65e/

Upvotes: 0

Views: 64

Answers (1)

Parkash Kumar
Parkash Kumar

Reputation: 4730

Change your $scope.nDays loop with the following which include comparasion of displayDate with current date, obviously you need to set time of d (current date) to 0 as your display date time is 0.

for (i = 1; i <= $scope.nDays; i++) {
    var d = new Date();
    d.setHours(0, 0, 0, 0);

    var displayDate = new Date($scope.year,  offsetDate, i);
    if(displayDate >= d)
        $scope.dateValues.push(displayDate);
}

DEMO

Upvotes: 1

Related Questions