Skip to content
Advertisement

Insert SubString in a time input type

I have an time calculator which returns an input type of time in the following format: hh/mm/ss

It currently displays like this:

Let time = "03:00:00"

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:

let testOne = ["02:00:00", "01:00:00", "01:00:00"]

function test () {
let calTotalHours = testOne.map(t => t.split(':')).reduce((arr,item,index)=>{

    arr[0]+= parseFloat(item[0]);
    arr[1]+= parseFloat(item[1]);
    arr[2]+= parseFloat(item[2]);

    if(arr[2]>=60) {
        arr[1]++;
        arr[2]%=60;
    }
    if(arr[1]>=60) {
        arr[0]++;
        arr[1]%=60;
    }
    return arr;
},[0,0,0])
    .join(':')
    console.log(calTotalHours)
}

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)

let testOne = ["02:00:00", "01:00:00", "01:00:00"]

function test() {
  let calTotalHours = testOne.map(t => t.split(':')).reduce((arr, item, index) => {

    arr[0] += parseFloat(item[0]);
    arr[1] += parseFloat(item[1]);
    arr[2] += parseFloat(item[2]);

    if (arr[2] >= 60) {
      arr[1]++;
      arr[2] %= 60;
    }
    if (arr[1] >= 60) {
      arr[0]++;
      arr[1] %= 60;
    }

    return arr;
  }, [0, 0, 0]).map((v) => (v < 10) ? v = "0" + v : v).join(':')
  console.log(calTotalHours)
}

test()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement