我是靠谱客的博主 坚强网络,这篇文章主要介绍js 随机生成时间段,现在分享给大家,希望可以做个参考。

这是一个没啥大用的功能,是因为有时候随机补量,或者让自己的数据做的更好看一些,需要随机生成一些时间段(对,就是作假时候用的)

需求

1、需要生成的时间段数量
2、生成时间的范围
3、每一天每个时间段的占比
这就是示意图了

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data() { return { thatTime: 0, // 获取要计算的开始时间 inputNumber: "", // 需要生成的数量 dataValue: null,// 时间段 // 时间的占比 scale1: "10", scale2: "20", scale3: "30", scale4: "40", // 生成的时间列表 list: [] }; }

1、默认将数量平均分到每一天

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 获取几天 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 循环获取每天的时间戳,获取占比

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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、生成规定段的随机数

复制代码
1
2
3
4
5
6
randomNum(lowerValue, upperValue) { return Math.floor( Math.random() * (upperValue - lowerValue + 1) + lowerValue ); }

结果

UI用的elementUI
在这里插入图片描述

详细代码:https://github.com/YaohuiHou/RandomTimePeriod

最后

以上就是坚强网络最近收集整理的关于js 随机生成时间段的全部内容,更多相关js内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部