如何将时间日期从时隙拆分为数组?

我有一个startDate和一个endDate,我想拆分成startDateendDate的数组吗?我的分配器是一个时隙(不是分页中的数字)。

我的打字稿代码是:

startDate: Date;
endDate: Date;
timeSlots: moment.Duration = moment.duration(30,'minutes');

我的startDate是2019-11-02T11:57:00.701Z,而我的endDate 2019-11-02T13:31:00.701Z

我在寻找如何击退此结果的方法:

[
  {startDate: 2019-11-02T11:57:00.701Z,endDate: 2019-11-02T12:26:59.701Z}
  {startDate: 2019-11-02T12:27:00.701Z,endDate: 2019-11-02T12:56:59.701Z}
  {startDate: 2019-11-02T12:57:00.701Z,endDate: 2019-11-02T13:26:59.701Z}
  {startDate: 2019-11-02T13:27:00.701Z,endDate: 2019-11-02T13:31:00.701Z}
]
wjhwu88 回答:如何将时间日期从时隙拆分为数组?

使用moment-range插件

window['moment-range'].extendMoment(moment);

const start  = moment('2019-11-02T11:57:00.701Z');
const end    = moment('2019-11-02T13:31:00.701Z');
const range  = moment.range(start,end);

const rangeBy = range.by('minutes',{ step: 30 });

const res = Array.from(rangeBy).map(m => ({
  'startTime': m.toISOString(),'endTime': m.add(29,'m').add(59,'s').toISOString()
}))

if(moment(res[res.length -1].endTime).isAfter(end)) {
  res[res.length -1].endTime = end.toISOString();
}

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>

本文链接:https://www.f2er.com/3166285.html

大家都在问