如何使用javascript将毫秒转换为"hhmmss"格式?

hae*_*ish 4 javascript datetime

我正在使用javascript Date对象尝试将毫秒转换为多少小时,分钟和秒.

我有以毫秒为单位的currentTime

var currentTime = new Date().getTime()
Run Code Online (Sandbox Code Playgroud)

我的futureTime以毫秒为单位

var futureTime = '1432342800000'
Run Code Online (Sandbox Code Playgroud)

我希望在毫秒内得到改变

var timeDiff = futureTime - currentTime
Run Code Online (Sandbox Code Playgroud)

timeDiff是

timeDiff = '2568370873'
Run Code Online (Sandbox Code Playgroud)

我想知道它是多少小时,分钟,秒.

有人可以帮忙吗?

tdb*_*bit 15

如果您确信该周期始终少于一天,您可以使用以下一句:

new Date(timeDiff).toISOString().slice(11,19)   // HH:MM:SS
Run Code Online (Sandbox Code Playgroud)

timeDiff注意:如果大于一天,这将是错误的。


ozi*_*zil 11

var secDiff = timeDiff / 1000; //in s
var minDiff = timeDiff / 60 / 1000; //in minutes
var hDiff = timeDiff / 3600 / 1000; //in hours  
Run Code Online (Sandbox Code Playgroud)

更新

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

var timespan = 2568370873; 
msToHMS( timespan );  
Run Code Online (Sandbox Code Playgroud)

演示

  • 我希望这是 hh/mm/ss。我怎样才能以这种格式获得它? (2认同)
  • 对于 203 秒,将为 0:0:2.34。格式错误! (2认同)

Mam*_*hid 10

将毫秒转换为 hh:mm:ss

function millisecondsToHuman(ms) {
  const seconds = Math.floor((ms / 1000) % 60);
  const minutes = Math.floor((ms / 1000 / 60) % 60);
  const hours = Math.floor((ms  / 1000 / 3600 ) % 24)

  const humanized = [
    pad(hours.toString(), 2),
    pad(minutes.toString(), 2),
    pad(seconds.toString(), 2),
  ].join(':');

  return humanized;
}
=
Run Code Online (Sandbox Code Playgroud)

  • `pad` 是在哪里定义的?我没有发现它是一个 Javascript 函数。 (6认同)