天天看点

JavaScript生成指定时间段的随机时间随机时间

随机时间

有时候我们在 mock 数据时需要生成一些随机时间值,如果单纯的使用毫米级别的时间戳作为开始时间和结束时间,生成的随机时间会出现超出正常时间范围的值,例如生成

2019-08-22 13:23:98

秒超出

60

秒的范围。

代码以供参考

const moment = require('moment');

const randomDate = (startDate, endDate) => {
  let date = new Date(+startDate + Math.random() * (endDate - startDate));
  let hour = 0 + Math.random() * (23 - 0) | 0;
  let minute = 0 + Math.random() * (59 - 0) | 0;
  let second = 0 + Math.random() * (59 - 0) | 0;
  date.setHours(hour);
  date.setMinutes(minute);
  date.setSeconds(second);
  return date;
};

// 生产当月的开始日期
const startDate = moment()
      .startOf('month')
      .toDate();
// 截止日期
const endDate = new Date();

const randomTime = moment(randomDate(startDate, endDate)).format('YYYY-MM-DD HH:mm:ss'); // '2019-08-14 21:19:36'
           

继续阅读