4

I want to convert the format example '00: 30: 00' on seconds. This is my way. Is there a way to add these values in the 'template string'?

expected effect:

convert1000('00:30:00') --> 1800

convert1000('00:00:10') --> 10

convert1000('00:08:10') --> 490

convert1000('01:01:10') --> 3670

const convert1000 = (time) => {
    const [hour, minute, sec] = time.split(':');

    if (hour !== "00") {
      return `${(hour* 3600)} + ${(minute * 60)} + ${(sec)}`;
    }

    if (minute !== "00") {
      return `${minute * 60} + ${sec} `;
    }

    return `${sec} `;
  }
Umbro
  • 1,748
  • 7
  • 32
  • 79

6 Answers6

6

Use asSeconds from momentjs duration objects

moment.duration('00:30:00').asSeconds();
Lucas
  • 1,475
  • 1
  • 14
  • 18
5

You could split and reduce the values by multiplying the former value by 60 and then add the value.

const convert1000 = time => time.split(':').reduce((s, t) => s * 60 + +t, 0);
  
console.log(convert1000('00:30:00')); // 1800
console.log(convert1000('00:00:10')); // 10
console.log(convert1000('00:08:10')); // 58 is wrong, because 8 minutes is 480 plus 10 sec
console.log(convert1000('01:01:10')); // 3670
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
2

You need to do it like this

const convert1000 = (time) => {
  const [h,m,s] = time.split(':');
  let seconds = (h*3600) + (m * 60) + parseInt(s);
  return seconds;
}

alert(convert1000("00: 30: 00"))

See the fiddle here https://jsfiddle.net/q4zvsowe/

Shridhar Sharma
  • 2,265
  • 1
  • 8
  • 13
2

You need to convert the string numbers into integers first. This should work the way you intend:

let convert1000 = (timeString) => {
    let [hour, minute, second] = timeString.split(':').map(Number);
    return `${(hour* 3600) + (minute * 60) + (second)}`;
}

Note that this returns a string; if you want it to be a number, just remove the templating.

Justin Gilman
  • 176
  • 1
  • 9
1

You need to put the + inside the braces to make them sum numbers.

You should put it inside one ${}

So your code would be like below:

const convert2000 = (time) => {
    const [hour, minute, sec] = time.split(':');

    if (hour !== "00") {
      return `${hour* 3600 + minute * 60 + sec}`;
    }

    if (minute !== "00") {
      return `${minute * 60 + sec} `;
    }

    return `${sec}`;
}
Alireza HI
  • 1,783
  • 1
  • 10
  • 20
0

Try this:

const convert1000 = (time) => {
  const [hour, minute, sec] = time.split(':');
  return hour * 3600 + minute * 60 + sec * 1;
};

console.log(convert1000('00:30:00'));
Feras Al Sous
  • 1,033
  • 1
  • 12
  • 23