基于ISO日期生成过去一周每日起止ISO时间区间数组的技术需求
Solution to Generate Daily UTC Date Ranges for the Past Week (Including Input Date)
Got it, let's fix this up for you! The core issue with your current code is that it's subtracting full days from the original timestamp (which has a specific time like 20:18:27) instead of adjusting each date to the start and end of the UTC day.
We'll use Day.js's built-in startOf() and endOf() methods to handle this cleanly, plus ensure we're working in UTC to avoid timezone mismatches (since your input uses the Z suffix for UTC).
Step-by-Step Correct Implementation
First, make sure you have Day.js installed (and the UTC plugin, which is required for proper UTC date handling):
# If using npm npm install dayjs
Here's the working code:
const dayjs = require('dayjs'); // Load the UTC plugin to avoid local timezone interference require('dayjs/plugin/utc'); dayjs.extend(require('dayjs/plugin/utc')); function getDailyDateRanges(inputDate) { const dateRanges = []; // Parse input as a UTC Day.js object to preserve the Z timezone marker const baseDate = dayjs.utc(inputDate); // Loop 8 times: cover the input date plus the 7 days before it for (let daysAgo = 7; daysAgo >= 0; daysAgo--) { // Calculate the target date by subtracting N days from the base date const targetDay = baseDate.subtract(daysAgo, 'day'); // Get the start of the target day (UTC 00:00:00.000) const dayStart = targetDay.startOf('day').toISOString(); // Get the end of the target day (UTC 23:59:59.000, matching your example format) const dayEnd = targetDay.endOf('day').millisecond(0).toISOString(); // Push the formatted range (with quotes as in your example) dateRanges.push([`"${dayStart}"`, `"${dayEnd}"`]); } return dateRanges; } // Test with your example input const input = '2021-09-18T20:18:27.000Z'; console.log(getDailyDateRanges(input));
Key Details Explained
- UTC Handling: Using
dayjs.utc(inputDate)ensures we don't accidentally convert the input to your local timezone, which would skew the start/end times away from UTC midnight. - Start/End of Day:
startOf('day')resets the time to00:00:00.000UTC, whileendOf('day')defaults to23:59:59.999UTC. We add.millisecond(0)to match your example's.000suffix exactly. - Loop Logic: We loop from 7 days ago down to 0 (the input date itself) to generate all 8 required date ranges.
Output Matching Your Example
When you run the code with your input, you'll get exactly the array you provided:
[ ['"2021-09-11T00:00:00.000Z"', '"2021-09-11T23:59:59.000Z"'], ['"2021-09-12T00:00:00.000Z"', '"2021-09-12T23:59:59.000Z"'], ['"2021-09-13T00:00:00.000Z"', '"2021-09-13T23:59:59.000Z"'], ['"2021-09-14T00:00:00.000Z"', '"2021-09-14T23:59:59.000Z"'], ['"2021-09-15T00:00:00.000Z"', '"2021-09-15T23:59:59.000Z"'], ['"2021-09-16T00:00:00.000Z"', '"2021-09-16T23:59:59.000Z"'], ['"2021-09-17T00:00:00.000Z"', '"2021-09-17T23:59:59.000Z"'], ['"2021-09-18T00:00:00.000Z"', '"2021-09-18T23:59:59.000Z"'] ]
内容的提问来源于stack exchange,提问作者hkimani
相关产品推荐
相关产品推荐

