如何在JavaScript中将毫秒时间转换为小时、分钟和秒的格式?

138
我有一段以毫秒为单位的时间,我想将它转换成“HH:MM:SS”格式。它应该会环绕,例如当milliseconds = 86400000时,我希望得到00:00:00
27个回答

203

那么创建一个类似这样的函数怎么样:

function msToTime(duration) {
  var milliseconds = Math.floor((duration % 1000) / 100),
    seconds = Math.floor((duration / 1000) % 60),
    minutes = Math.floor((duration / (1000 * 60)) % 60),
    hours = Math.floor((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;
}
console.log(msToTime(300000))


我曾尝试使用这种方法将毫秒转换为小时:分钟:秒的格式,但是结果不正确。它只会给出21:11:05的值。请问我该如何实现正确的转换? - cheliyan
1
var s = st_date+' '+start; var e = end_date+' '+end; var bits = s.split(/\D/); var bits1 = e.split(/\D/); var date = new Date(bits[0], --bits[1], bits[2], bits[3], bits[4],bits[5]); var date1 = new Date(bits1[0], --bits1[1], bits1[2], bits1[3], bits1[4],bits1[5]);将st_date和start合并为s; 将end_date和end合并为e; 使用/\D/分隔符拆分s和e生成bits和bits1数组; 根据bits数组中的年、月、日、时、分、秒,创建起始日期date对象; 根据bits1数组中的年、月、日、时、分、秒,创建结束日期date1对象。 - cheliyan
var t1 = date.getTime(); var t2 = date1.getTime(); var t3 = date1.getTime() - date.getTime();var seconds; var minutes; var milliseconds = parseInt((t3 % 1000) / 100), seconds = parseInt((t3 / 1000) % 60), minutes = parseInt((t3 / (1000 * 60)) % 60), hours = parseInt((t3 / (1000 * 60 * 60)) % 24);hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds;duration = hours + ":" + minutes + ":" + seconds; alert('dur::' + t3); alert('duration:' + duration); - cheliyan
2
如果持续时间输入参数已经是毫秒,为什么要除以100来获取毫秒?难道不应该只是parseInt(duration % 1000)吗? - NoBullMan
4
应该是 var milliseconds = Math.floor(duration % 1000); 这样写。 - pseudozach
显示剩余6条评论

89

将毫秒时间转换为易读的时间格式。

function msToTime(ms) {
  let seconds = (ms / 1000).toFixed(1);
  let minutes = (ms / (1000 * 60)).toFixed(1);
  let hours = (ms / (1000 * 60 * 60)).toFixed(1);
  let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
  if (seconds < 60) return seconds + " Sec";
  else if (minutes < 60) return minutes + " Min";
  else if (hours < 24) return hours + " Hrs";
  else return days + " Days"
}

console.log(msToTime(1000))
console.log(msToTime(10000))
console.log(msToTime(300000))
console.log(msToTime(3600000))
console.log(msToTime(86400000))

"Out Put Sample"


5
我认为这个最有用,在我的测试中,排名第一的答案似乎不能很好地处理小时,并且这个也可以让你选择天数。 - ak85
太棒了!谢谢。 - Björn C
6
我认为这个答案并不有帮助。"3.7"小时是什么意思? - Sartheris Stormhammer

34

我有同样的问题,这是我最终做出的解决方案:

function parseMillisecondsIntoReadableTime(milliseconds){
  //Get hours from milliseconds
  var hours = milliseconds / (1000*60*60);
  var absoluteHours = Math.floor(hours);
  var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;

  //Get remainder from hours and convert to minutes
  var minutes = (hours - absoluteHours) * 60;
  var absoluteMinutes = Math.floor(minutes);
  var m = absoluteMinutes > 9 ? absoluteMinutes : '0' +  absoluteMinutes;

  //Get remainder from minutes and convert to seconds
  var seconds = (minutes - absoluteMinutes) * 60;
  var absoluteSeconds = Math.floor(seconds);
  var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;


  return h + ':' + m + ':' + s;
}


var time = parseMillisecondsIntoReadableTime(86400000);

alert(time);


25

这是我的解决方案

let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);

// 获取时间格式 00:00:00

s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`


console.log(`${s}:${m}:${h}`);

6
在三元运算符之外,我会为变量s赋值:s = \${s < 10 ? '0': ''}${s}` `。这行代码的作用是将数字s转换为两位数的字符串形式,并在其前面添加'0'以实现对齐。 - seniorpreacher

22

这个函数返回类似于YouTube视频的时间

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

输出:

  • getYoutubeLikeToDisplay(129900) = "2:10"
  • getYoutubeLikeToDisplay(1229900) = "20:30"
  • getYoutubeLikeToDisplay(21229900) = "05:53:50"

注释 – 对于负时间,例如“-3000”,应该显示“-00:03”,但实际上它返回“-1:0-03”。 - anu
我进行了一些改进/调整。https://dev59.com/DWIj5IYBdhLWcg3w_5vl#67462589 - Sinjai

16

抱歉,来晚了。被接受的答案对我没用,所以我自己写了一个。

2h 59s
1h 59m
1h
1h 59s
59m 59s
59s

代码(TypeScript):

function timeConversion(duration: number) {
  const portions: string[] = [];

  const msInHour = 1000 * 60 * 60;
  const hours = Math.trunc(duration / msInHour);
  if (hours > 0) {
    portions.push(hours + 'h');
    duration = duration - (hours * msInHour);
  }

  const msInMinute = 1000 * 60;
  const minutes = Math.trunc(duration / msInMinute);
  if (minutes > 0) {
    portions.push(minutes + 'm');
    duration = duration - (minutes * msInMinute);
  }

  const seconds = Math.trunc(duration / 1000);
  if (seconds > 0) {
    portions.push(seconds + 's');
  }

  return portions.join(' ');
}

console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)              ));
console.log(timeConversion((60 * 60 * 1000)                                 ));
console.log(timeConversion((60 * 60 * 1000)                    + (59 * 1000)));
console.log(timeConversion(                   (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion(                                      (59 * 1000)));

1
谢谢,这正是我想要的。不过需要稍作调整以显示“0小时0分钟10秒”等内容,但除此之外很简洁明了。 - HazeyAce
1
我开始写我的代码,然后我想,肯定有人已经做过这个了 :). 谢谢! - Ben S

7
以上代码片段无法处理超过1天的情况(简单地被忽略)。
为此,您可以使用以下代码:
function convertMS(ms) {
    var d, h, m, s;
    s = Math.floor(ms / 1000);
    m = Math.floor(s / 60);
    s = s % 60;
    h = Math.floor(m / 60);
    m = m % 60;
    d = Math.floor(h / 24);
    h = h % 24;
    h += d * 24;
    return h + ':' + m + ':' + s;
}

在此输入图像描述

感谢https://gist.github.com/remino/1563878


1
为了获得更加人性化的输出,你可以返回类似这样的内容:return ((h + '').length === 1 ? '0'+ h : h) + ':' + ('0' + m).substr(-2) + ':' + ('0' + s).substr(-2); - Vitall
@Vitall 只需使用 return (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);,因为用数学计算比字符串操作更好。 - Mitch McMabers

6

以可选填充方式格式化为hh:mm:ss

(1:59:5901:59:59)
(1:5901:59)
(默认:不填充)

基于 Chand 的回答稍作修改。

function formatMilliseconds(milliseconds, padStart) {
    function pad(num) {
        return `${num}`.padStart(2, '0');
    }
    let asSeconds = milliseconds / 1000;

    let hours = undefined;
    let minutes = Math.floor(asSeconds / 60);
    let seconds = Math.floor(asSeconds % 60);

    if (minutes > 59) {
        hours = Math.floor(minutes / 60);
        minutes %= 60;
    }

    return hours
        ? `${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}`
        : `${padStart ? pad(minutes) : minutes}:${pad(seconds)}`;
}

测试:

let s = 1000;
let m = 60*s;
let h = 60*m;
console.log(formatMilliseconds(1*h));               // 1:00:00
console.log(formatMilliseconds(1*h, true));         // 01:00:00
console.log(formatMilliseconds(59*m + 59*s));       // 59:59
console.log(formatMilliseconds(59*m + 59*s, true)); // 59:59
console.log(formatMilliseconds(9*m + 9*s));         // 9:09
console.log(formatMilliseconds(9*m + 9*s, true));   // 09:09
console.log(formatMilliseconds(5*s));               // 0:05
console.log(formatMilliseconds(5*s, true));         // 00:05
console.log(formatMilliseconds(2400*s));            // 40:00
console.log(formatMilliseconds(2400*s, true));      // 40:00

如果您需要毫秒级精度,可以使用以下方法获取小数部分:
(asSeconds % 1).toFixed(3).substring(1)

你的返回结果可能会像这样(如果需要,可以将其拆分以提高可读性):
`${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`

可能有更好的方法来实现这个目标,但这种朴素的解决方案能够完成工作。

测试:

let asSeconds = 59.5219;
let seconds = Math.floor(asSeconds);
console.log(`${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Equivalent to above, without using `pad()`:
//console.log(`${String(seconds).padStart(2, '0')}${(asSeconds % 1).toFixed(3).substring(1)}`);

// Output: 59.522

这并不满足OP对24小时环绕到00:00:00的要求(但是你表达的不是持续时间而是时钟上的时间吗?) - Sinjai
这可能是一个更明智和惯用的方法,只获取小数点后三位数字:secondString = asSeconds.toFixed(3); secondString.substring(secondString.indexOf('.')); - Sinjai

6

我只需要一天的时间,24小时,这是我的想法:


const milliseconds = 5680000;

const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);

const time = `${hours}:${minutes}:${seconds}`
console.log(time);

您也可以使用这种方式获取天数(如果需要)。

5
本解决方案使用一个函数将毫秒划分为“parts object”,另一个函数将格式化该“parts object”。我创建了两个格式化函数,一个按照您的要求,另一个打印出友好的字符串并考虑单数/复数,并包括显示毫秒的选项。

function parseDuration(duration) {
  let remain = duration

  let days = Math.floor(remain / (1000 * 60 * 60 * 24))
  remain = remain % (1000 * 60 * 60 * 24)

  let hours = Math.floor(remain / (1000 * 60 * 60))
  remain = remain % (1000 * 60 * 60)

  let minutes = Math.floor(remain / (1000 * 60))
  remain = remain % (1000 * 60)

  let seconds = Math.floor(remain / (1000))
  remain = remain % (1000)

  let milliseconds = remain

  return {
    days,
    hours,
    minutes,
    seconds,
    milliseconds
  };
}

function formatTime(o, useMilli = false) {
  let parts = []
  if (o.days) {
    let ret = o.days + ' day'
    if (o.days !== 1) {
      ret += 's'
    }
    parts.push(ret)
  }
  if (o.hours) {
    let ret = o.hours + ' hour'
    if (o.hours !== 1) {
      ret += 's'
    }
    parts.push(ret)
  }
  if (o.minutes) {
    let ret = o.minutes + ' minute'
    if (o.minutes !== 1) {
      ret += 's'
    }
    parts.push(ret)

  }
  if (o.seconds) {
    let ret = o.seconds + ' second'
    if (o.seconds !== 1) {
      ret += 's'
    }
    parts.push(ret)
  }
  if (useMilli && o.milliseconds) {
    let ret = o.milliseconds + ' millisecond'
    if (o.milliseconds !== 1) {
      ret += 's'
    }
    parts.push(ret)
  }
  if (parts.length === 0) {
    return 'instantly'
  } else {
    return parts.join(' ')
  }
}

function formatTimeHMS(o) {
  let hours = o.hours.toString()
  if (hours.length === 1) hours = '0' + hours

  let minutes = o.minutes.toString()
  if (minutes.length === 1) minutes = '0' + minutes

  let seconds = o.seconds.toString()
  if (seconds.length === 1) seconds = '0' + seconds

  return hours + ":" + minutes + ":" + seconds
}

function formatDurationHMS(duration) {
  let time = parseDuration(duration)
  return formatTimeHMS(time)
}

function formatDuration(duration, useMilli = false) {
  let time = parseDuration(duration)
  return formatTime(time, useMilli)
}


console.log(formatDurationHMS(57742343234))

console.log(formatDuration(57742343234))
console.log(formatDuration(5423401000))
console.log(formatDuration(500))
console.log(formatDuration(500, true))
console.log(formatDuration(1000 * 30))
console.log(formatDuration(1000 * 60 * 30))
console.log(formatDuration(1000 * 60 * 60 * 12))
console.log(formatDuration(1000 * 60 * 60 * 1))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接