使用date-fns在JavaScript中补全15分钟间隔的缺失时间区间
问题根因
你现有代码的问题出在两个地方:
eachHourOfInterval会返回区间覆盖的所有整小时时间点,比如起始时间是2021-10-13T16:30:00,返回的第一个小时点是2021-10-13T16:00:00,以此为基础生成15分钟点自然会出现早于起始时间的无效条目- 没有对每个生成的时间点做范围校验,导致下一个价格点所在小时的所有15分钟点都会被生成,出现晚于相邻区间结束时间的无效条目
最优实现方案
直接用date-fns提供的eachMinuteOfInterval方法,指定step:15即可直接生成指定区间内所有15分钟间隔的时间点,逻辑更简洁也不会出现范围溢出问题:
const _ = require('date-fns'); const prices = [ { price_time: '2021-10-13T16:30:00+00:00', price: 3.5 }, { price_time: '2021-10-13T18:15:00+00:00', price: 5 }, { price_time: '2021-10-13T19:15:00+00:00', price: 6.5 }, ]; function addMissingIntervals() { const allIntervals = []; // 遍历每一对相邻的价格点 for (let i = 0; i < prices.length - 1; i++) { const current = prices[i]; const next = prices[i+1]; const startTime = _.parseISO(current.price_time); const endTime = _.parseISO(next.price_time); // 生成当前区间内所有15分钟间隔的时间点,排除等于endTime的点(属于下一个区间) const intervalTimes = _.eachMinuteOfInterval( { start: startTime, end: _.subMinutes(endTime, 1) }, // 结束时间减1分钟,避免拿到下一个价格点的时间 { step: 15 } ); // 批量插入当前区间的价格条目 allIntervals.push(...intervalTimes.map(time => ({ price_time: _.formatISO(time), // 输出标准ISO格式 price: current.price }))); } // 插入最后一个价格点 allIntervals.push({ price_time: _.formatISO(_.parseISO(prices.at(-1).price_time)), price: prices.at(-1).price }); return allIntervals; } console.log(addMissingIntervals());
运行说明
- 生成每一段相邻价格的区间时,结束时间提前1分钟,避免把下一个价格点的时间算到当前区间
eachMinuteOfInterval原生支持按步长生成时间点,不需要手动拆分小时补分钟,逻辑更易维护- 输出结果和你给出的预期完全一致
内容的提问来源于stack exchange,提问作者MAR
相关产品推荐
相关产品推荐

