1

假设我有一个 ISO 日期,例如2021-09-18T20:18:27.000Z

  1. 我想以数组的形式获取过去一周的日期
  2. 该数组应该是一组数组,其中包含两个 ISO 日期,分别代表一天的开始和结束,如下图所示:

例如

输入:

2021-09-18T20:18:27.000Z

输出:

[
['"2021-09-11T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-12T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-13T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-14T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-15T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-16T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-17T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-18T00:00:00.000Z', '"2021-09-18T23:59:59.000Z'],
]

我已经用 dayjs 试过了,这会导致数组表示从特定日期开始的确切间隔:

function getDates(date) {
  var dates = [date]
  var noOfDays = 7

  for (let i = noOfDays - 1; i >= 0; i--) {
    const elementIndex = i - noOfDays // Get last nth element of the list
    const dateToIncrement = dates.slice(elementIndex)[0]
    const newDate = dayjs(dateToIncrement).subtract(1, "day").toISOString()
    dates.unshift(newDate)
  }
  return dates
}

谢谢

4

2 回答 2

2
function getPastWeek(inputTime) {
    var res = []; //result array
    var currentDayEnd = undefined; //variable to be set on each iteration
    var currentDay = new Date(inputTime.split('T')[0]); //create new Date object
    currentDay.setDate(currentDay.getDate() - 7); //reduce seven days from current date

    for(var i = 0; i <= 7; i++) { //foreach day in last week
        currentDayEnd = new Date(currentDay.getTime() - 1000); //previous day end (1sec before current day start)
        currentDayEnd.setDate(currentDayEnd.getDate() + 1); //current day end (one day after previous day end)
        res.push([currentDay.toISOString(), currentDayEnd.toISOString()]); //append pair

        currentDay.setDate(currentDay.getDate() + 1); //set variable to next day
    }

    return res;
}

var pastWeek = getPastWeek('2021-09-18T20:18:27.000Z'); //call example

于 2021-09-18T21:38:26.193 回答
1

OP 代码非常接近,您应该能够根据需要对其进行调整。下面采用类似的算法。一天结束设置为午夜前 1 毫秒。

// Given a UTC ISO 8601 timestamp, return array of day plus 
// previous 6 days with start of day, end of day timestmaps
function getDates(d) {
  let s = new Date(d.slice(0,10));
  let e = new Date(+s);
  e.setUTCHours(23,59,59,999);
  let result = [];

  for (let i=7; i; i--) {
    result.push([s.toISOString(), e.toISOString()]);
    s.setUTCDate(s.getUTCDate() - 1);
    e.setUTCDate(e.getUTCDate() - 1);
  }
  return result;
}

console.log(getDates(new Date().toISOString()));

于 2021-09-19T21:48:05.067 回答