Ayesha
Ayesha

Reputation: 905

Show future date using javascript in dropdown. (dynamically each time)

I have the jsfiddle http://jsfiddle.net/92yv2h9n/

As you can see, the first option of dropdown shows the current date. The next two options should show the future dates.

for e.g- today is 11th dec. so future date of 12th dec and 13th dec should be shown. currently it shows the present date only. Its in mm-dd-yyyy format.

Can someone please highlight how can i achieve the future dates.

PS- It should automatically note that feb has 28 days and dec will have 31 days and so on.

Here is the code.

JS code

function Ctrl($scope) {
$scope.date = new Date();
}

HTML code

<div ng-app ng-controller="Ctrl">
<select>
<option>{{date | date:'MM-dd-yyyy'}}</option>
<option>{{date | date:'MM-dd-yyyy'}}</option>
<option>{{date | date:'MM-dd-yyyy'}}</option>
</select>
</div>

Upvotes: 0

Views: 891

Answers (1)

bstockwell
bstockwell

Reputation: 514

Convert the date to millis and add a day of milliseconds onto it (or 2 days for the second one):

<div ng-app ng-controller="Ctrl">
  <select>
    <option>{{date.getTime() | date:'MM-dd-yyyy'}}</option>
    <option>{{(date.getTime() + (1000 * 60 * 60 * 24)) | date:'MM-dd-yyyy'}}</option>
    <option>{{(date.getTime() + (1000 * 60 * 60 * 48)) | date:'MM-dd-yyyy'}}</option>
  </select>
</div>

even shorter version using ng-repeat:

<div ng-app ng-controller="Ctrl">
  <select>
    <option ng-repeat="date in [0,1,2]">{{date.getTime() + (1000 * 60 * 60 * 24 * day)| date:'MM-dd-yyyy'}}</option>
  </select>
</div>

Avoid weekends:

<div ng-app ng-controller="Ctrl">
  <select>
    <option ng-repeat="day in dates">{{date | date:'MM-dd-yyyy'}}</option>
  </select>
</div>

Controller:

function Ctrl($scope) {
    $scope.baseAdd = 0;
  $scope.dates = [0,1,2].map(function(day) {
    dateobj = new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * (day + $scope.baseAdd)));
        while(dateobj.getDay() == 6 || dateobj.getDay() == 0) {
      dateobj = new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * (day + $scope.baseAdd++)));
    }
    console.log(dateobj)
    return dateobj;
});
}

Upvotes: 2

Related Questions