【问题标题】:How can I convert milliseconds to "hhmmss" format using javascript?如何使用 javascript 将毫秒转换为“hhmmss”格式?
【发布时间】:2015-04-23 07:44:11
【问题描述】:

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

我有当前时间(以毫秒为单位)

var currentTime = new Date().getTime()

我有以毫秒为单位的 futureTime

var futureTime = '1432342800000'

我想以毫秒为单位获得差异

var timeDiff = futureTime - currentTime

timeDiff 是

timeDiff = '2568370873'

我想知道它是多少小时、分钟、秒。

有人可以帮忙吗?

【问题讨论】:

  • 一分钟是60秒,一小时是60分钟。
  • 我只使用一个衬垫new Date(timeInMS).toISOString().substr(11, 8); 'HH:MM:SS'

标签: javascript datetime


【解决方案1】:
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours  

更新

function msToHMS( ms ) {
    // 1- Convert to seconds:
    let seconds = ms / 1000;
    // 2- Extract hours:
    const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours
    // 3- Extract minutes:
    const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
    // 4- Keep only seconds not extracted to minutes:
    seconds = seconds % 60;
    alert( hours+":"+minutes+":"+seconds);
}

const timespan = 2568370873; 
msToHMS( timespan );  

Demo

【讨论】:

  • 我希望这是 hh/mm/ss。我怎样才能拥有这种格式?
  • 对于 203 秒,它将是 0:0:2.34。格式错误!
  • 我参加聚会有点晚了,但我在下面发布了一个更正的版本。
【解决方案2】:

如果您确信该周期将始终少于一天,则可以使用此单行:

new Date(timeDiff).toISOString().slice(11,19)   // HH:MM:SS

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

【讨论】:

    【解决方案3】:

    将 ms 转换为 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;
    }
    =
    

    【讨论】:

      【解决方案4】:
      function msToHMS( duration ) {
      
           var milliseconds = parseInt((duration % 1000) / 100),
              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 ;
      }
      

      【讨论】:

      • 如果你想超过 24 小时,那么编辑这一行: hours = parseInt((duration / (1000 * 60 * 60)));"。删除 '% 24'。
      【解决方案5】:

      将毫秒转换为hh:mm:ss 格式的字符串。这是我的版本:

      function HHMMSSFromMilliseconds(ms) {
        // 1- Convert to seconds:
        var seconds = ms / 1000;
      
        // 2- Extract hours:
        var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
        seconds = parseInt(seconds % 3600); // extract the remaining seconds 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 = parseInt(seconds % 60);
      
        // 5 - Format so it shows a leading zero if needed
        let hoursStr = ("00" + hours).slice(-2);
        let minutesStr = ("00" + minutes).slice(-2);
        let secondsStr = ("00" + seconds).slice(-2);
      
        return hoursStr + ":" + minutesStr + ":" + secondsStr
      }
      
      let timespan = 23570 * 1000;
      let formattedTime = HHMMSSFromMilliseconds(timespan);
      
      console.log(formattedTime);

      【讨论】:

        【解决方案6】:

        时间差以毫秒为单位: Get time difference between two dates in seconds

        要获得差异,您必须使用 math.floor() http://www.w3schools.com/jsref/jsref_floor.asp

        var secDiff = Math.floor(timeDiff / 1000); //in s
        var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
        var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
        

        【讨论】:

        • secDiff 以秒为单位给出 timeDiff。我希望将整个 timeDiff 转换为 hh:mm:ss 格式。不仅仅是将 timeDiff 转换为秒或分钟或小时。有没有办法做到这一点?
        • 据我所知,您必须使用 timediff 中已知的毫秒数来建立一个新的日期。这个新的日期对象包含您需要的信息。
        • @GijsbertBrouwer——日期对象只是一个毫秒值(和一堆方法),所以一旦你有了毫秒的差异,你就拥有与日期一样多的数据。 ;-)
        【解决方案7】:
        var timediff = futureTime - currentTime
        long seconds = (long) (timediff / 1000) % 60 ;
        long minutes = (long) ((timediff / (1000*60)) % 60);
        long hours   = (long) ((timediff / (1000*60*60)) % 24);
        if(hours>0)
            time = hours+" hrs : "+minutes+" mins";
        else if(minutes>0)
            time = minutes+" mins";
        else if(seconds>0)
            time = seconds+" secs";
        

        【讨论】:

          【解决方案8】:

          这是一个简单的函数

          function simplifiedMilliseconds(milliseconds) {
          
            const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
            const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
            const totalHours = parseInt(Math.floor(totalMinutes / 60));
            const days = parseInt(Math.floor(totalHours / 24));
          
            const seconds = parseInt(totalSeconds % 60);
            const minutes = parseInt(totalMinutes % 60);
            const hours = parseInt(totalHours % 24);
          
            let time = '1s';
            if (days > 0) {
              time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
            } else if (hours > 0) {
              time = `${hours}h:${minutes}m:${seconds}s`;
            } else if (minutes > 0) {
              time = `${minutes}m:${seconds}s`;
            } else if (seconds > 0) {
              time = `${seconds}s`;
            }
            return time;
          }
          

          【讨论】:

            【解决方案9】:

            将毫秒转换为 DD(天):HH:MM:SS

            function formatTime(timeMS) {
                const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
                let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
                const days = Math.floor(seconds / SEC_IN_DAY);
                seconds = Math.floor(seconds % SEC_IN_DAY);
                const hours = Math.floor(seconds / SEC_IN_HOUR);
                seconds = Math.floor(seconds % SEC_IN_HOUR);
                const minutes = Math.floor(seconds / SEC_IN_MIN);
                seconds = Math.floor(seconds % SEC_IN_MIN);
                const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
                    .map(item => item < 10 ? '0' + item : item.toString());
                return dd + ':' + hh + ':' + mm + ':' + ss;
            }
            
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-02-20
              • 2014-12-18
              • 2022-09-27
              • 1970-01-01
              • 1970-01-01
              • 2021-08-07
              • 2014-02-13
              • 1970-01-01
              相关资源
              最近更新 更多