I want to convert seconds into minutes.
For example 61 seconds should be displayed like 1:01 (not 1:1)
I tried with parseInt(sec / 60) : sec % 60.
If sec=61 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. I have to add 0 before 1 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:01.
Thank you for your help in advance.
CodePudding user response:
function parseTime(time) {
const minutes = Math.floor(time / 60);
const second = time % 60;
// return `${minutes}:${second < 10 ? "0" : ""}${second}`;
return `${minutes}:${second.toString().padStart(2, "0")}`;
}
You can use the if else statement to verify the second or use padStart to make sure the length of the second is always 2.
CodePudding user response:
try this
const convertToTime = (time) => (time < 10 ? `0${time}` : time);
const sec = 69;
const result = `${convertToTime(parseInt(sec / 60))}:${convertToTime(sec % 60)}`;;
console.log(result);
CodePudding user response:
Thank you all for your support. I found the answer. Thank to @ace1234
{parseInt(data.duration / 60)} : {parseFloat(data.duration % 60 ).toString().padStart(2, "0")
CodePudding user response:
You can write a logic to handle it or use padStart
const something = 7;
const fun1 = (s) => s < 10 ? `0${s}` : s;
const fun2 = (s) => s.toString().padStart(2, '0');
console.log( fun1(something) );
console.log( fun2(something) );
CodePudding user response:
Do it like
let min = sec/60;
And display like
min: sec - (min*60)
