這是一個沒啥大用的功能,是因爲有時候隨機補量,或者讓自己的數據做的更好看一些,需要隨機生成一些時間段(對,就是作假時候用的)
需求
1、需要生成的時間段數量
2、生成時間的範圍
3、每一天每個時間段的佔比
代碼
data() {
return {
thatTime: 0, // 獲取要計算的開始時間
inputNumber: "", // 需要生成的數量
dataValue: null,// 時間段
// 時間的佔比
scale1: "10",
scale2: "20",
scale3: "30",
scale4: "40",
// 生成的時間列表
list: []
};
}
1、默認將數量平均分到每一天
// 獲取幾天
let date = Date.parse(this.dataValue[1]) - Date.parse(this.dataValue[0]);
let day = date / 1000 / 60 / 60 / 24 + 1;
// 劃分每天的數量
let dayNum = this.inputNumber / day;
this.thatTime = Date.parse(this.dataValue[0]);
for (let index = 0; index < day; index++) {
// 循環每一天,將每天需要生成的數量和當前的天數傳入
this.getDateFun(dayNum, index)
}
2、getDateFun 循環獲取每天的時間戳,獲取佔比
getDateFun(dayNum, index) {
let arr = [];
for (let i = 0; i < dayNum; i++) {
let endMe = 0;
let me = 1000 * 60 * 60;
if (i <= (Number(this.scale1) / 100) * dayNum) {
// 0~6
me *= 6;
} else if (
i > (Number(this.scale1) / 100) * dayNum &&
i <= ((Number(this.scale2) + Number(this.scale1)) / 100) * dayNum
) {
// 6~12
endMe = 1000 * 60 * 60 * 6;
me *= 12;
} else if (
i > ((Number(this.scale2) + Number(this.scale1)) / 100) * dayNum &&
i <=
((Number(this.scale2) + Number(this.scale1) + Number(this.scale3)) /
100) *
dayNum
) {
// 12~18
endMe = 1000 * 60 * 60 * 12;
me *= 18;
} else if (
i >
((Number(this.scale2) + Number(this.scale1) + Number(this.scale3)) /
100) *
dayNum &&
i <= dayNum
) {
// 18~24
endMe = 1000 * 60 * 60 * 18;
me *= 24;
}
// 插入
// randomNum 生成隨機數的區間
var date = new Date(this.randomNum(endMe, me) + this.thatTime);
var Y = date.getFullYear() + "-";
var M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var m =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var s =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
arr.push(Y + M + D + " " + h + ":" + m + ":" + s);
}
console.log(arr);
this.list.push(arr.sort());
console.log(this.list);
this.thatTime += 86400000;
}
3、生成規定段的隨機數
randomNum(lowerValue, upperValue) {
return Math.floor(
Math.random() * (upperValue - lowerValue + 1) + lowerValue
);
}
結果
UI用的elementUI
詳細代碼:https://github.com/YaohuiHou/RandomTimePeriod