Suppose I have an ISO date, such as 2021-09-18T20:18:27.000Z
E.g.
input:
2021-09-18T20:18:27.000Z
output:
[
['"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'],
]
I've already tried it with dayjs, this results in the array representing exact intervals from a particular date:
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
}
Thank you
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