I have an time calculator which returns an input type of time in the following format: hh/mm/ss
It currently displays like this:
JavaScript
x
2
1
Let time = "03:00:00"
2
When I do a calculate function it return “3:0:0” instead and removes the “0”.
How can I change this to be 03:00:00? The “0” must only be added if the h/m/s is less then 10.
Here are my calculate function if needed. The function returns the sum of time fron an array:
JavaScript
1
23
23
1
let testOne = ["02:00:00", "01:00:00", "01:00:00"]
2
3
function test () {
4
let calTotalHours = testOne.map(t => t.split(':')).reduce((arr,item,index)=>{
5
6
arr[0]+= parseFloat(item[0]);
7
arr[1]+= parseFloat(item[1]);
8
arr[2]+= parseFloat(item[2]);
9
10
if(arr[2]>=60) {
11
arr[1]++;
12
arr[2]%=60;
13
}
14
if(arr[1]>=60) {
15
arr[0]++;
16
arr[1]%=60;
17
}
18
return arr;
19
},[0,0,0])
20
.join(':')
21
console.log(calTotalHours)
22
}
23
Advertisement
Answer
You need to add the zeros after the reduce, since reduce is still calculating the time.
I added a .map
after the calculation to get each value of time and then check if value is less than 10:
.map((v) => (v < 10) ? v = "0" + v : v)
JavaScript
1
24
24
1
let testOne = ["02:00:00", "01:00:00", "01:00:00"]
2
3
function test() {
4
let calTotalHours = testOne.map(t => t.split(':')).reduce((arr, item, index) => {
5
6
arr[0] += parseFloat(item[0]);
7
arr[1] += parseFloat(item[1]);
8
arr[2] += parseFloat(item[2]);
9
10
if (arr[2] >= 60) {
11
arr[1]++;
12
arr[2] %= 60;
13
}
14
if (arr[1] >= 60) {
15
arr[0]++;
16
arr[1] %= 60;
17
}
18
19
return arr;
20
}, [0, 0, 0]).map((v) => (v < 10) ? v = "0" + v : v).join(':')
21
console.log(calTotalHours)
22
}
23
24
test()