javascript中的日期数组 [英] Array of dates in javascript

查看:76
本文介绍了javascript中的日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个日期:开始和结束

我使用这些日期创建了一系列日期。



开始日期= 11 / 1/2018 Enddate = 4/31/2019



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



问题是它会正确创建日期数组,除非它是月初或月末。 />


因此,如果我的开始日期是11/1/2018且enddate是04/31/2019,那么阵列打印错误的日期,否则它可以正常工作。



不知道我在这里做错了什么。感谢任何帮助。



我尝试过:



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;
}

推荐答案

while (startDate < endDate) {
    arr.push(new Date(startDate));
    startDate.setDate(endDate.getDate() );
    startDate.setMonth(startDate.getMonth() + 1);
}


这篇关于javascript中的日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆