95

Soundcloud's API gives the duration of it's tracks as milliseconds. JSON looks like this:

"duration": 298999

I've tried many functions I found on here to no avail. I'm just looking for something to convert that number to something like looks like this:

4:59

Here's one that got close, but doesn't work. It doesn't stop the seconds at 60. It goes all the way to 99 which makes no sense. Try entering "187810" as a value of ms, for example.

var ms = 298999,
min = Math.floor((ms/1000/60) << 0),
sec = Math.floor((ms/1000) % 60);

console.log(min + ':' + sec);

Thanks for your help!

If you could add in support for hours, too, I would be grateful.

4

12 回答 12

225
function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

millisToMinutesAndSeconds(298999); // "4:59"
millisToMinutesAndSeconds(60999);  // "1:01"

正如用户HelpingHand在评论中指出的那样,return 语句应该是:

return (
  seconds == 60 ?
  (minutes+1) + ":00" :
  minutes + ":" + (seconds < 10 ? "0" : "") + seconds
);
于 2014-01-22T21:43:17.647 回答
19

小时,0-填充分钟和秒:

var ms = 298999;
var d = new Date(1000*Math.round(ms/1000)); // round to nearest second
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
console.log(str); // 0:04:59

于 2014-01-22T21:33:39.590 回答
8

我不太确定为什么这些答案都如此复杂。该Date课程为您提供所需的:

const date = new Date(298999);

alert(`${date.getMinutes()}:${date.getSeconds()}`);

尽管上述内容符合 op 的要求,但添加此更新版本以响应 @ianstarz 关于时区独立性的评论:

const d = new Date(Date.UTC(0,0,0,0,0,0,298999)),
  // Pull out parts of interest
  parts = [
    d.getUTCHours(),
    d.getUTCMinutes(),
    d.getUTCSeconds()
  ],
  // Zero-pad
  formatted = parts.map(s => String(s).padStart(2,'0')).join(':');

alert(formatted);

于 2021-09-10T03:08:11.737 回答
5

如果寻找,这是我的贡献

时:分:秒

而不是像我一样:

function msConversion(millis) {
  let sec = Math.floor(millis / 1000);
  let hrs = Math.floor(sec / 3600);
  sec -= hrs * 3600;
  let min = Math.floor(sec / 60);
  sec -= min * 60;

  sec = '' + sec;
  sec = ('00' + sec).substring(sec.length);

  if (hrs > 0) {
    min = '' + min;
    min = ('00' + min).substring(min.length);
    return hrs + ":" + min + ":" + sec;
  }
  else {
    return min + ":" + sec;
  }
}
于 2019-06-02T01:45:51.887 回答
3

最好的是这个!

function msToTime(duration) {
var milliseconds = parseInt((duration%1000))
    , seconds = parseInt((duration/1000)%60)
    , minutes = parseInt((duration/(1000*60))%60)
    , hours = parseInt((duration/(1000*60*60))%24);

hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;

return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

它将返回 00:04:21.223 您可以根据需要格式化此字符串。

于 2019-10-21T20:07:35.917 回答
3

虽然事件,oment.js 不提供这样的功能,如果你来到这里并且你已经在使用 moment.js,试试这个:

function formatDuration(ms) {
  var duration = moment.duration(ms);
  return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
}

你会得到类似 x:xx:xx 的东西。

在这种情况下,您可能希望跳过小时,而持续时间仅为 < 60 分钟。

function formatDuration(ms) {
  var duration = moment.duration(ms);
  if (duration.asHours() > 1) {
    return Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss");
  } else {
    return moment.utc(duration.asMilliseconds()).format("mm:ss");
  }
}

问题中介绍了此解决方法。

于 2016-02-18T21:49:28.253 回答
1

可能有更好的方法来做到这一点,但它可以完成工作:

var ms = 298999;
var min = ms / 1000 / 60;
var r = min % 1;
var sec = Math.floor(r * 60);
if (sec < 10) {
    sec = '0'+sec;
}
min = Math.floor(min);
console.log(min+':'+sec);

不知道为什么您的分钟行中有 << 运算符,我认为在显示前几分钟就不需要它。

用 % 获得剩余的分钟数可以得到该分钟所用秒数的百分比,因此将它乘以 60 可以得到秒数,并且地板使它更适合显示,尽管如果你也可以获得亚秒级精度想。

如果秒小于 10,您希望以前导零显示它们。

于 2014-01-22T21:43:37.143 回答
0
function msToHMS( ms ) {
  // 1- Convert to seconds:
  var seconds = ms / 1000;

  // 2- Extract hours:
  var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
  seconds = seconds % 3600; // seconds remaining after extracting hours

  // 3- Extract minutes:
  var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute

  // 4- Keep only seconds not extracted to minutes:
  seconds = seconds % 60;

  //alert( hours+":"+minutes+":"+seconds);
  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;
  var hms = hours+":"+minutes+":"+seconds;
  return hms;
}
于 2020-07-17T15:03:08.057 回答
-1

只是工作:

const minute = Math.floor(( milliseconds % (1000 * 60 * 60)) / (1000 * 60));

const second = Math.floor((ms % (1000 * 60)) / 1000);
于 2020-03-30T20:41:48.320 回答
-1

我的解决方案:输入:11381(以毫秒为单位)输出:00:00:11.381

 timeformatter(time) {
    console.log(time);

    let miliSec = String(time%1000);
    time = (time - miliSec)/1000;
    let seconds = String(time%60);
    time = (time - seconds)/60;
    let minutes = String(time%60);
    time = (time-minutes)/60;
    let hours = String(time)

    while(miliSec.length != 3 && miliSec.length<3 && miliSec.length >=0) {
        miliSec = '0'+miliSec;
    }
    while(seconds.length != 2 && seconds.length<3 && seconds.length >=0) {
        seconds = '0'+seconds;
    }
    while(minutes.length != 2 && minutes.length<3 && minutes.length >=0) {
        minutes = '0'+minutes;
    }
    while(hours.length != 2 && hours.length<3 && hours.length >=0) {
        hours = '0'+hours;
    }
    return `${hours}  : ${minutes} : ${seconds}.${miliSec}`
}
于 2020-12-16T11:28:26.850 回答
-1
const Minutes = ((123456/60000).toFixed(2)).replace('.',':');

//Result = 2:06

我们将以毫秒为单位的数字 (123456) 除以 60000,得到相同的以分钟为单位的数字,此处为 2.0576。

toFixed(2) - 将数字四舍五入到最接近的两位小数,在本例中给出的答案为 2.06。

然后,您使用 replace 将句点交换为冒号。

于 2020-10-14T11:45:29.907 回答
-2

如果您想在 1:02:32.21 等秒后显示小时和厘秒或毫秒,此代码会做得更好,如果在手机中使用,即使在屏幕锁定后,计时器也会显示正确的时间。

<div id="timer" style="font-family:monospace;">00:00<small>.00</small></div>

<script>
var d = new Date();
var n = d.getTime();
var startTime = n;

var tm=0;
function updateTimer(){
  d = new Date();
  n = d.getTime();
  var currentTime = n;  
  tm = (currentTime-startTime);
  
  //tm +=1; 
  // si el timer cuenta en centesimas de segundo
  //tm = tm*10;
  
  var hours = Math.floor(tm / 1000 / 60 / 60);
  var minutes = Math.floor(tm / 60000) % 60;
  var seconds =  ((tm / 1000) % 60);
  // saca los decimales ej 2 d{0,2}
  var seconds = seconds.toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];
  var miliseconds = ("00" + tm).slice(-3);
  var centiseconds;

  
  // si el timer cuenta en centesimas de segundo
  //tm = tm/10;


  centiseconds = miliseconds/10;
  centiseconds = (centiseconds).toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];

  minutes = (minutes < 10 ? '0' : '') + minutes;
  seconds = (seconds < 10 ? '0' : '') + seconds;
  centiseconds = (centiseconds < 10 ? '0' : '') + centiseconds;
  hours = hours + (hours > 0 ? ':' : '');
  if (hours==0){
    hours='';
  }

  document.getElementById("timer").innerHTML = hours + minutes + ':' + seconds + '<small>.' + centiseconds + '</small>';
}

var timerInterval = setInterval(updateTimer, 10);
// clearInterval(timerInterval);
</script>

于 2017-09-23T07:54:44.700 回答