Home > database >  How to convert minutes and seconds of audio/video to currentTime in javascript?
How to convert minutes and seconds of audio/video to currentTime in javascript?

Time:05-19

I have the string of video time is "02:30" and video.duration of video is 239. Now, how to convert "02:30" to currentTime?

CodePudding user response:

Use split(":") can solve that, i hope below will help you:

function convert(str){
  let a = str.split(':')
  return Number(a[0]) * 60   Number(a[1])
}
const currentTime = convert('02:30')
console.log("currentTime is", currentTime)

CodePudding user response:

A one line solution

If you want a simple one line solution you could use Array.reduce. Note that split returns a string[2], but we convert these to numbers by applying math operators, for example mm is shorthand for Number(mm). Also see MDN JavaScript arrow functions

let toMinutes = hhmm => hhmm.split(":").reduce((hh, mm) =>  mm   60 * hh );

Run the code snippet to view test output

let toMinutes = hhmm => hhmm.split(":").reduce((hh, mm) =>  mm   60 * hh );

// TEST

["00:30", "1:00", "01:15", "1:30", "01:45", "2:00", "2:15", "2:30", "2:45", "3:00", "24:00" ].forEach(t => {

  console.log(`${t} = ${toMinutes(t)} minutes`)
  
});

  • Related