0

I'm attempting to create an array of dates in Javascript based on a start date and an end date. I need the date format to look like 2013-04-25

My code apparently doesn't work, but I can't seem to figure out why. Can someone assist?

//get today's date
var today = new Date();
today.setDate(today.getDate());

//get date from last week -7
var prevWeek = new Date();
prevWeek.setDate(prevWeek.getDate() -7);

//set initial date parameters
  var fromDate = prevWeek;
  var toDate = today;

//set date parameters to input parameters
function setDates() {
    fromDate =document.getElementById('fromDate').value;
    toDate = document.getElementById('toDate').value;
};

var dates = new Array();

//create date array
function setArray() {
    for(i = fromDate.getDate(), i <= toDate.getDate(), i.setDate(i.getDate() +1))
    {
    dates.push(new Date(i));
    };
};

//format date array
function formDates() {
    for(i = 0, i <= dates.length, i++)
    {
        var dd = dates[i].getDate();
        var mm = dates[i].getMonth()+1;
        var yyyy = dates[i].getFullYear();
        if(dd<10)   {dd = '0' + dd};
        if(mm<10){mm = '0' + mm};
        dates[i] = yyyy + '-' + mm + '-' + dd;
    };
};
3
  • 5
    you say it doesn't work. What are you experiencing. Nothing at all? or do you have errors? Commented Apr 25, 2013 at 15:02
  • 1
    Your setArray() is giving you troubles, I would rethink that loop also your loop signatures are wrong. they should be delimited with ;. - jslint.org + if you could give us your HTML that would be great :) Commented Apr 25, 2013 at 15:03
  • @limelights, that was the problem! I was using , instead of ;. Commented Apr 25, 2013 at 15:11

1 Answer 1

3

Your loop signatures are wrong.

They should be delimited with ; and not a ,

A correct javascript for loop is made like this:

for(var i = 0; i <= 1000; i++){
}

Using var statements here are also considered best practice due to javascript otherwise hoisting your i variable making it global to the function, or worst case scenario, your entire js-file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.