1

I have the following button group:

<div class="btn-group">
    <label class="btn btn-primary" data-btn-radio="'CurrentDateMinus3'">{{dateMinus3 | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDateMinus2'">{{dateMinus2 | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDateMinus1'">{{dateMinus1 | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDate'">{{date | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDatePlus1'">{{datePlus1 | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDatePlus2'">{{datePlus2 | date:'dd'}}</label>
    <label class="btn btn-primary" data-btn-radio="'CurrentDatePlus3'">{{datePlus3 | date:'dd'}}</label>
</div>

I found following AngularJS code in a StackOverflow question to set the dates:

var d = $scope.date = new Date();
$scope.dateMinus1 = d.setDate(d.getDate() - 1);
$scope.dateMinus2 = d.setDate(d.getDate() - 2);
$scope.dateMinus3 = d.setDate(d.getDate() - 3);
$scope.datePlus1 = d.setDate(d.getDate() + 1);
$scope.datePlus2 = d.setDate(d.getDate() + 2);
$scope.datePlus3 = d.setDate(d.getDate() + 3);

I want button group to display the dates in the following manner (using today's date and setting it as the middle button):

14 15 16 17 18 19 20

When I implement this code though, I get the following numbers in the buttons:

11 14 16 17 12 14 17

I could use some advice as to what I'm doing wrong. As far as I can tell, the code looks like it should work, but obviously its not. I appreciate any help.

2 Answers 2

2

That happens because variable d rewrited every time you call d.setDate(d.getDate() - 1). You need to call new Date() every time, or find another way to do it. (probably momentjs will help you)

0

Try setting dates in another way, because you need a new date each time.

var d = $scope.date = new Date();
var dates = [];
// loop to generate dates from -3 days ago to 3 days plus
for(var i=-3; i<= 3; i++){
     var today = new Date();
     dates.push(today.setDate(today.getDate() + i));
}
console.log(dates); 

Working example:

http://plnkr.co/edit/3kKxOq7jIUEay9JxLZbg?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.