获取两个时刻之间的日期/时间

时间:2019-01-26 09:19:40

标签: javascript node.js momentjs

我正在使用Node.JS和出色的Moment库。我有一个需要生成未来日期议程的功能(例如约会系统)

我有两个时间戳,代表一个时间段的开始和结束。

我想在这两次之间创建一个日期/时间数组,具体取决于当天的特定日期和时间。

一个例子是:

START DATE: 2019-01-26 15:00:01 (Saturday)
END DATE: 2019-02-23 15:00:00 (also a Saturday)
WE NEED: EVERY SATURDAY @ 1500

EXPECTED ARRAY:

2019-02-02 15:00:00
2019-02-09 15:00:00
2019-02-16 15:00:00
2019-02-23 15:00:00

请注意:数组中不包含开始位置,因为它比我们要查找的时间晚(一秒钟)。

关于如何在Node中完成此操作的任何想法?

2 个答案:

答案 0 :(得分:0)

const moment = require('moment')
const formatDate = date => moment(date).format('MMMM Do YYYY, h:mm:ss a')

const START_DATE = '2019-01-26 15:00:00'
const END_DATE = '2019-02-23 15:00:00'

let current = formatDate(START_DATE)
const end = formatDate(END_DATE)
let days = 7

let result = []
while (current > end) {
  current = moment(START_DATE).add(days, 'days')
  current = formatDate(current)
  result.push(current)
  days += 7
}
result.push(end)

result.forEach(date=>console.log(date))

答案 1 :(得分:0)

import moment from 'moment';

const getDaysBetween = (startDate, endDate, day, time) => {


  // Define a first day of result

  let firstDay = moment(startDate)
  .day(day)
  .set('hour', time.match(/[\d]+(?=:)/g)[0])
  .set('minutes', time.match(/(?<=:)[\d]+/g)[0])
  .set('seconds', 0);

  let resultDates = [ firstDay ];


  // Add the rest

  let weekBetweenThese = endDate.diff(firstDay, 'week');

  Array(weekBetweenThese).fill({}).forEach((d, i) => {
    resultDates.push(moment(firstDay).add(i + 1, 'weeks'))
  });


  // Filter out somecase that result day match with startDate & endDate but time condition goes wrong

  resultDates = resultDates.filter(resultDate =>
    startDate <= resultDate &&
    resultDate <= endDate
  );

  return resultDates.map(resultDate => resultDate.toDate());
  // return resultDates; // Return array of moment date.

};

console.log(
  getDaysBetween(
    moment('2019-01-26 15:00:01'),
    moment('2019-02-23 15:00:00'),
    'Saturday', '15:00'
  )
)

https://codesandbox.io/s/wkpz72mo9w