我需要生成两个给定日期之间的所有日期的序列。然而我无法获得想要的输出。
我尝试使用下面的代码。我得到一个空数组。
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate = currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
当我执行console.log(getDates("2019-10-10","2019-11-20"))
时,我得到的结果为空数组。结果我没有得到一系列日期。
最佳答案
正如@RobG提到的,解析日期可以 yield different results因此考虑使用以下内容:
function parseDate(input) {
var parts = input.split('-');
return new Date(parts[0], parts[1] - 1, parts[2]);
}
function getDates(startDate, endDate) {
var dates = [];
var currentDate = parseDate(startDate);
endDate = parseDate(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));
原始答案:
您可以将 endDate
更改为 Date
类型,而不设置 currentDate
,因为 setDate
会为您执行此操作:
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
endDate = new Date(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));
关于javascript - 使用简化方法生成两个给定日期之间的一系列日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882475/