Click here to Skip to main content
15,667,436 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 dates: start and end
I have created an array of dates using those dates.

Start date = 11/1/2018 Enddate = 4/31/2019

array = [11/1/2018,12/1/2018,1/1/2019,2/1/2019....4/1/2019]

The issue is that it creates the date array properly unless it's the beginning or end of month.

So if my start date is 11/1/2018 and enddate is 04/31/2019, then the array is printing wrong dates otherwise it works fine.

Not sure what i am doing wrong here. Any help is appreciated.

What I have tried:

 function getDateArray (start, end) {
        var arr = [];
        var startDate = new Date(start);
        console.log(startDate);
        var endDate = new Date(end);
        console.log(endDate);

        var ddlPayType = document.getElementById("payType");
        var selectedPayType = ddlPayType.options[ddlPayType.selectedIndex].value;
        var selectedFrequency;
        if (document.getElementById("ddFrequency"))
            selectedFrequency = document.getElementById("ddFrequency").value;

        if (selectedPayType) {
            if (selectedPayType === "A") {
                endDate.setMonth(endDate.getMonth());
            }
            else if (selectedPayType === "B") {
                endDate.setMonth(endDate.getMonth() + 1);
            }
        }
        while (startDate <= endDate) {
         
                        arr.push(new Date(startDate));
                        startDate.setDate(endDate.getDate()+1);
                        startDate.setMonth(startDate.getMonth() +1);
                    }
               
           
            return arr;
}
Posted
Updated 2-Nov-18 4:19am
v2
Comments
Patrice T 1-Nov-18 16:54pm    
Define 'wrong dates', show an example
Patrice T 1-Nov-18 17:04pm    
By the way, define also what is the meaning of this list.
Bryian Tan 1-Nov-18 17:34pm    
By the way, 04/31/2019 is not a valid date.
Patrice T 1-Nov-18 23:36pm    
"Start date = 11/1/2018 Enddate = 4/31/2018"
By the way, I fear the end date is before the start date.
F-ES Sitecore 2-Nov-18 6:25am    
4/31/2018 - that isn't valid for me in the UK, it isn't valid for people in Japan, but it is valid for people in America. How does your javascript know that you are an American?

1 solution

while (startDate < endDate) {
    arr.push(new Date(startDate));
    startDate.setDate(endDate.getDate() );
    startDate.setMonth(startDate.getMonth() + 1);
}
 
Share this answer
 
Comments
Member 14013562 2-Nov-18 10:18am    
This doesn't work. It prints the wrong range of dates and totally skips a month.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900