javascript converts seconds into time

In JavaScript, you can use the following code to convert seconds to time:

function secondsToTime(seconds) {
  var hours = Math.floor(seconds / 3600);
  var minutes = Math.floor((seconds - (hours * 3600)) / 60);
  var seconds = seconds - (hours * 3600) - (minutes * 60);
 
  // round seconds
  seconds = Math.round(seconds * 100) / 100
 
  var result = (hours < 10 ? "0" + hours : hours);
    result += ":" + (minutes < 10 ? "0" + minutes : minutes);
    result += ":" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

Instructions:

var time = secondsToTime(125);  // '00:02:05'

In this code, we first calculate the hours, then the minutes, and finally the seconds. Finally, we use string concatenation to combine these three parts into a time string and return it.

 Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/135080477