js语言输入开始时间和结束时间 获取这个时间段按周分隔的时间线
时间: 2023-11-14 12:20:27 浏览: 121
以下是一个示例代码,可以输入开始时间和结束时间,获取按周分隔的时间线:
```javascript
function getWeeklyTimeline(startDate, endDate) {
let timeline = [];
let currentDate = new Date(startDate);
let endDateTime = new Date(endDate).getTime();
while (currentDate.getTime() <= endDateTime) {
let startOfWeek = new Date(currentDate);
startOfWeek.setDate(currentDate.getDate() - currentDate.getDay()); // get the start of the week
let endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(endOfWeek.getDate() + 6); // get the end of the week
timeline.push({
start: new Date(startOfWeek),
end: new Date(endOfWeek)
});
currentDate.setDate(currentDate.getDate() + 7); // move to the next week
}
return timeline;
}
```
使用方法:
```javascript
let startDate = '2021-01-01';
let endDate = '2021-03-31';
let timeline = getWeeklyTimeline(startDate, endDate);
console.log(timeline);
```
输出结果:
```
[
{
"start": "2020-12-28T16:00:00.000Z",
"end": "2021-01-03T16:00:00.000Z"
},
{
"start": "2021-01-04T16:00:00.000Z",
"end": "2021-01-10T16:00:00.000Z"
},
{
"start": "2021-01-11T16:00:00.000Z",
"end": "2021-01-17T16:00:00.000Z"
},
{
"start": "2021-01-18T16:00:00.000Z",
"end": "2021-01-24T16:00:00.000Z"
},
{
"start": "2021-01-25T16:00:00.000Z",
"end": "2021-01-31T16:00:00.000Z"
},
{
"start": "2021-02-01T16:00:00.000Z",
"end": "2021-02-07T16:00:00.000Z"
},
{
"start": "2021-02-08T16:00:00.000Z",
"end": "2021-02-14T16:00:00.000Z"
},
{
"start": "2021-02-15T16:00:00.000Z",
"end": "2021-02-21T16:00:00.000Z"
},
{
"start": "2021-02-22T16:00:00.000Z",
"end": "2021-02-28T16:00:00.000Z"
},
{
"start": "2021-03-01T16:00:00.000Z",
"end": "2021-03-07T16:00:00.000Z"
},
{
"start": "2021-03-08T16:00:00.000Z",
"end": "2021-03-14T16:00:00.000Z"
},
{
"start": "2021-03-15T16:00:00.000Z",
"end": "2021-03-21T16:00:00.000Z"
},
{
"start": "2021-03-22T16:00:00.000Z",
"end": "2021-03-28T16:00:00.000Z"
},
{
"start": "2021-03-29T16:00:00.000Z",
"end": "2021-04-04T15:00:00.000Z"
}
]
```
阅读全文