Home > Software design >  How to convert seconds to minutes?
How to convert seconds to minutes?

Time:01-17

I want to convert seconds into minutes. For example 70 seconds should be displayed like 1:10 (not 1:1) I tried with parseInt(sec / 60) : sec % 60. If sec=70 it is showing like 1:1.

I have data from music API that gives me music duration in seconds and I have to convert them into minutes. I tried

{parseInt(data.duration / 60 )} : {data.duration % 60}

sometimes it is giving me 3:35, 3:24 and 3:1. it is removing 0 from the end. I have to add this 0 into my result as well. How can I do it I also tried with

{parseInt(data.duration / 60 )} : {parseFloat(data.duration % 60).toFixed(2)}

it is showing 1:1.00 I want to display it like 1:10.

Thank you for your help in advance.

CodePudding user response:

I tried with js snippset then the result is OK. I think you have some missed, read carefully your code and compare with below:

var sec = 70;

var minute = (parseInt(sec/60));
var second = (sec`);

console.log(minute ":" second);
// output: 1:10

CodePudding user response:

Here is the solution:

function convertHMS(value) {
    const sec = parseInt(value, 10); // convert value to number if it's string
    let hours   = Math.floor(sec / 3600); // get hours
    let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
    let seconds = sec - (hours * 3600) - (minutes * 60); //  get seconds
    // add 0 if value < 10; Example: 2 => 02
    if (hours   < 10) {hours   = "0" hours;}
    if (minutes < 10) {minutes = "0" minutes;}
    if (seconds < 10) {seconds = "0" seconds;}
    return hours ':' minutes ':' seconds; // Return is HH : MM : SS
}

console.log(convertHMS(70)) // 00:01:10

CodePudding user response:

try this

const convertToTime = (time) => (time < 10 ? (time = `0${time}`) : time);

const sec = 69;
const result = `${convertToTime(parseInt(sec / 60))}:${convertToTime(sec % 60)}`;;

console.log(result);

CodePudding user response:

Do it like

let min = sec/60;

And display like

min: sec - (min*60)

  •  Tags:  
  • Related