js使用使用到Math.random()方法实现在一个时间范围内产生一个随机时间。
/*在时间范围内产生一个随机时间*/
function randomDate(start, end) {
if (start != null && end != null) {
const _start = new Date(start).getTime();
const _end = new Date(end).getTime();
const differ = _end - _start;
const time_stamp = Math.random() * differ;
const time = _start + time_stamp;
//格式化时间
const datetime = new Date();
datetime.setTime(time);
const year = datetime.getFullYear();
const month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
const date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate();
const hour = datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours();
const minute = datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes();
const second = datetime.getSeconds() < 10 ? '0' + datetime.getSeconds() : datetime.getSeconds();
return year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
} else {
return '---';
}
}
//调用方法
//console.info('开始时间:' + start_.value + '\n' + '结束时间:' + end_.value + '\n' + '随机生成时间:' + randomDate(start_.value, end_.value));
运行效果: