如何使用JavaScript将秒转换为HH-MM-SS字符串?


当前回答

var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;

alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))

 /* ----------------------------------------------------------
 *  Field        | Full Form          | Short Form
 *  -------------|--------------------|-----------------------
 *  Year         | yyyy (4 digits)    | yy (2 digits)
 *  Month        | MMM (abbr.)        | MM (2 digits)
                 | NNN (name)         |
 *  Day of Month | dd (2 digits)      | 
 *  Day of Week  | EE (name)          | E (abbr)
 *  Hour (1-12)  | hh (2 digits)      | 
 *  Minute       | mm (2 digits)      | 
 *  Second       | ss (2 digits)      | 
 *  ----------------------------------------------------------
 */
function DateFormat(formatString,date){
    if (typeof date=='undefined'){
    var DateToFormat=new Date();
    }
    else{
        var DateToFormat=date;
    }
    var DAY         = DateToFormat.getDate();
    var DAYidx      = DateToFormat.getDay();
    var MONTH       = DateToFormat.getMonth()+1;
    var MONTHidx    = DateToFormat.getMonth();
    var YEAR        = DateToFormat.getYear();
    var FULL_YEAR   = DateToFormat.getFullYear();
    var HOUR        = DateToFormat.getHours();
    var MINUTES     = DateToFormat.getMinutes();
    var SECONDS     = DateToFormat.getSeconds();

    var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var strMONTH;
    var strDAY;
    var strHOUR;
    var strMINUTES;
    var strSECONDS;
    var Separator;

    if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
        strMONTH = "0" + MONTH;
    else
        strMONTH=MONTH;
    if(parseInt(DAY)< 10 && DAY.toString().length < 2)
        strDAY = "0" + DAY;
    else
        strDAY=DAY;
    if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
        strHOUR = "0" + HOUR;
    else
        strHOUR=HOUR;
    if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
        strMINUTES = "0" + MINUTES;
    else
        strMINUTES=MINUTES;
    if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
        strSECONDS = "0" + SECONDS;
    else
        strSECONDS=SECONDS;

    switch (formatString){
        case "hh:mm:ss":
            return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
        break;
        //More cases to meet your requirements.
    }
}

其他回答

看了所有的答案,大部分都不满意,下面是我想到的。我知道我说得有点晚了,但我还是要说了。

function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}

我创建了一个新的日期对象,将时间更改为参数,将日期对象转换为时间字符串,并通过分割字符串并只返回需要的部分来删除额外的内容。

我认为我应该分享这种方法,因为它不需要正则表达式、逻辑和数学技巧来获得“HH:mm:ss”格式的结果,而是依赖于内置的方法。

您可能想看一下这里的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

更新(2020):

请使用@Frank的一句话解决方案:

new Date(SECONDS * 1000).toISOString().substring(11, 16)

如果SECONDS<3600并且你只想显示MM:SS,那么使用下面的代码:

new Date(SECONDS * 1000).toISOString().substring(14, 19)

这是目前为止最好的解决办法。


旧的回答:

使用Moment.js库。

Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string. Number.prototype.toHHMMSS = function() { var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600); var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2); var seconds = ("00" + (this % 3600) % 60).slice(-2); return hours + ":" + minutes + ":" + seconds; } // Usage: [number variable].toHHMMSS(); // Here is a simple test var totalseconds = 1234; document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS(); // HTML of the test <div id="timespan"></div>

我认为标准Date对象的任何内置特性都不会以一种比自己做数学更方便的方式为您做这件事。

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

例子:

let totalSeconds = 28565; let hours = Math.floor(totalSeconds / 3600); totalSeconds %= 3600; let minutes = Math.floor(totalSeconds / 60); let seconds = totalSeconds % 60; console.log("hours: " + hours); console.log("minutes: " + minutes); console.log("seconds: " + seconds); // If you want strings with leading zeroes: minutes = String(minutes).padStart(2, "0"); hours = String(hours).padStart(2, "0"); seconds = String(seconds).padStart(2, "0"); console.log(hours + ":" + minutes + ":" + seconds);

var  timeInSec = "661"; //even it can be string

String.prototype.toHHMMSS = function () { 
   /* extend the String by using prototypical inheritance */
    var seconds = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    seconds = seconds - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
}

alert("5678".toHHMMSS());   // "01:34:38"
console.log(timeInSec.toHHMMSS());   //"00:11:01"

我们可以把这个函数写得更短更清晰,但这会降低可读性,所以我们要把它写得尽可能简单,尽可能稳定。

或者你可以在这里检查一下: