javaScript-时间相加,超过24小时继续累加
# 需求
例如:23小时20分20秒 + 15小时20分20秒
# 实现
// 时间计算
addTime(time1, time2) {
let regex = /(\d+)小时(\d+)分(\d+)秒/;
var time1= time1.match(regex)
var time2= time2.match(regex)
var hours1 = Number(time1[1])
var minutes1 = Number(time1[2])
var seconds1 = Number(time1[3])
var hours2 = Number(time2[1])
var minutes2 = Number(time2[2])
var seconds2 = Number(time2[3])
var totalSeconds = seconds1 + seconds2;
var totalMinutes = minutes1 + minutes2 + Math.floor(totalSeconds / 60);
var totalHours = hours1 + hours2 + Math.floor(totalMinutes / 60);
totalSeconds %= 60;
totalMinutes %= 60;
return `${this.pad(totalHours)}小时${this.pad(totalMinutes)}分${this.pad(totalSeconds)}秒`;
},
// 个位数要补充0
pad(num) {
return num.toString().padStart(2, '0');
},
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2024/02/29, 15:10:43