JavaScript 如何存储给定两个日期之间的所有日期的数组
给定两个日期,任务是使用JavaScript获取两个给定日期之间的日期数组。
以下是以下方法:
- 使用push()方法
- 使用for循环和push()方法
方法1:使用push()方法
- 选择第一个和最后一个日期,并将其存储在一个变量中。
- 检查开始日期是否小于停止日期,然后将当前日期推入一个数组,并将其值增加1天。
- 重复上述步骤,直到当前日期等于最后一个日期。
示例: 在此示例中,日期数组由上述方法确定。
Date.prototype.addDay = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDate(strDate, stpDate) {
let dArray = new Array();
let cDate = strDate;
while (cDate <= stpDate) {
// Adding the date to array
dArray.push(new Date(cDate) + '<br>');
// Increment the date by 1 day
cDate = cDate.addDay(1);
}
return dArray;
}
function GFG_Fun() {
let startDate = new Date();
// Making lastDate equal to 4 more days
// from startDate.
let endDate = startDate.addDay(4);
console.log(getDate(startDate, endDate));
}
GFG_Fun();
输出
[
'Tue Jul 18 2023 18:59:06 GMT+0000 (Coordinated Universal Time)<br>',
'Wed Jul 19 2023 18:59:06 GMT+0000 (Coordinated Universal Time)<br>',
'Thu Jul 20 2023 18:59:06 GMT+0000 (Coordinated Univ...
方法2:使用 for循环 和 push()方法
- 获取第一个和最后一个日期,并将其存储到一个变量中。
- 计算1天相当于毫秒数,称为_1Day。
- 设置一个变量等于开始日期,称为ms。
- 将ms(毫秒)以日期形式推入一个数组中,并将其值增加_1Day。
- 重复上述步骤,直到ms等于最后一个日期为止。
示例: 在这个示例中,日期数组是通过以上方法确定的。
Date.prototype.addDay = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
function getDates(date1, date2) {
let _1Day = 24 * 3600 * 1000;
// Date[] keeps all the dates
let dates = [];
for (let ms = date1.getTime(), last = date2.getTime();
ms <= last; ms += _1Day) {
dates.push(new Date(ms));
}
return dates;
}
function GFG_Fun() {
let startDate = new Date();
// Making lastDate equal to 4 more days
// from startDate
let endDate = startDate.addDay(4);
console.log(getDates(startDate, endDate));
}
GFG_Fun();
输出
[
2023-07-18T19:12:03.831Z,
2023-07-19T19:12:03.831Z,
2023-07-20T19:12:03.831Z,
2023-07-21T19:12:03.831Z,
2023-07-22T19:12:03.831Z
]