使用Javascript将毫秒转换为分钟和秒钟 [英] Converting milliseconds to minutes and seconds with Javascript

查看:3284
本文介绍了使用Javascript将毫秒转换为分钟和秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Soundcloud的API给出了其音轨的持续时间(以毫秒为单位). JSON看起来像这样:

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

这里是一个接近但无法正常工作的人.它不会使秒数在60处停止.它一直上升到99,这毫无意义.例如,尝试输入"187810"作为ms值.

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);

感谢您的帮助!

如果您也可以增加几个小时的支持,我将不胜感激.

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

推荐答案

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语句应为

As User HelpingHand pointed in the comments the return statement should be

返回(秒== 60?(分钟+1)+:00":分钟+:" +(秒<10?"0":")+秒);

return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);

这篇关于使用Javascript将毫秒转换为分钟和秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆