我的开始日期为任何月份的星期一,结束日期为任何月份的星期日。我需要介于日期之间的周列表。例如我选择开始日期为08/12/2019,结束日期为09/08/2019。作为输出,需要周列表。所以
{[08/12/2019,08/13/2019,08/14/2019,08/15/2019,08/16/2019,08/17/2019,08/18/2019],[08/19/2019,08/20/2019,08/21/2019,08/22/2019,08/23/2019,08/24/2019,08/25/2019],[08/26/2019,08/27/2019,08/28/2019,08/29/2019,08/30/2019,08/31/2019,09/01/2019],[09/02/2019,09/03/2019,09/04/2019,09/05/2019,09/06/2019,09/07/2019,09/08/2019]}
在react hook / js中需要。
var start = new Date("08/12/2019");
var end = new Date("09/08/2019");
var newStart = start.setDate(start.getDate()+7);
var days = [];
for (var d = begin; d <= newStart; d = d + 1) {
days.push(new Date(d));
}
这只能使用1周,没有太大帮助。
答案 0 :(得分:0)
您可以使用嵌套循环扩展解决方案:
const start = new Date("2019-08-12");
const end = new Date("2019-09-08");
const DAY = 24 * 60 * 60 * 1000;
const weeks = [];
for (let newStart = start.valueOf(); newStart < end; newStart += DAY * 7) {
const days = [];
for (let d = newStart; d < newStart + 7 * DAY; d += DAY) {
days.push(new Date(d));
}
weeks.push(days);
}
console.log(weeks);
注意:
YYYY-MM-DD
用于UTC的零时偏移,以避免随机的时偏移
new Date(d).toJSON().slice(0, 10)
会将日期转换为这种格式的字符串+
运算符的正确行为
d + 1
会将其转换为字符串并将其与'1'连接,因此我将d
用作数字以确保+
是一个数字加d += DAY
与d = d + DAY
for
中使用let来实现适当的块作用域(var
将在函数作用域中声明变量)答案 1 :(得分:0)
第二种简单的方法如下所示,您无需使用双循环。
function getWeeks(startDate, endDate){
var sd = new Date(startDate);
var weeks = [];
var week = [];
var weekCounter = 1; // you can remove this
for (var d = sd; d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
week.push(new Date(d).getMonth()+1 +'/'+new Date(d).getDate()+'/'+new Date(d).getFullYear());
if(new Date(d).getDay() == 0)
{
weeks.push("Week"+weekCounter + ":"); // you can remove this
weeks.push(week);
weekCounter++; // you can remove this
week = [];
}
}
return weeks;
}
console.log(getWeeks('08/12/2019','09/08/2019'));