思路就是时间段之间的时间差乘以随机就可以了,代码如下:
<script type="text/javascript">
//时间戳转换成时间
function timestampTotimestr(timestamp) {
var date = new Date(timestamp);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1): date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = (date.getHours() < 10 ? '0' + date.getHours(): date.getHours()) + ':';
m = (date.getMinutes() < 10 ? '0' + date.getMinutes(): date.getMinutes()) + ':';
s = date.getSeconds() < 10 ? '0' + date.getSeconds(): date.getSeconds();
return Y+M+D+h+m+s;
}
//时间转换成时间戳
function timestrTotimestamp(str) {
return (new Date(str)).getTime();
}
function randomDate(start, end, startHour, endHour) {
var date = new Date(+start + Math.random() * (end - start));
var hour = startHour + Math.random() * (endHour - startHour) | 0;
date.setHours(hour);
return date;
}
//生成2021-10-12值25之间,时辰是10点到20点的随机时间
console.log(timestampTotimestr(randomDate(timestrTotimestamp("2021-10-12 00:00:00"), timestrTotimestamp("2021-10-25 00:00:00"), 10, 20)));
</script>
网友回复