Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Set date object using a variable

I have a question related to the date object in Javascript. I am trying to make a control that goes to the next day. The problem is I need the date in d[0] so I can pop and unshift.

var x=1;

var y;

var g = new Date();

var d = new Date();

d = [];

d[0] = g.setDate(g.getDate());

while (x < 6 && x > 0) {
            d[x] = g.setDate(g.getDate() - 1);
            x++;
}

function nextDay () {

 y = g.setDate(g.getDate() + 1);// want to use d[0] instead of getDate

 console.log(y);
};

2 Answers

You could preformat the date then when scrolled place a new date object one the array set to the date format string. ( sorry for no code example on phone)

The formatting is not the problem. It is iterating through the dates so that I can get to the next day (or previous). All I really need is how to set the date from an array. Example - The array has 26th December as the latest date, and I need to add 27th December to it and remove 21st December. So I must know where I am in the list. Thanks for your help.

I used 0 position as a separate object to compare. Your approach is correct.

Have you checked out to MDN documentation on the date object? You could just get the current day the add one with out all the other stuff. Why do you need to have an array of dates?

Yes I have. The problem is the array needs the 0 position so I have a scroll-able list of dates(once the user starts scrolling I need the current object and the correct dates to add into the array). If you have suggestions to do a list of dates that we can scroll through. I am using the bootstrap pagination for the HTML.