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


当前回答

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>

其他回答

已经有很多答案了,但我的要求是:

转换为持续时间(即,应适用于大于24小时的值) 关心的小数秒到给定的十进制精度 如果为零,则截断前面的小时和分钟。

const seconds2duration = ( seconds, decimals=0 ) => { let fraction = ( seconds - Math.floor( seconds ) ).toFixed( decimals ); fraction = decimals === 0 ? '' : fraction.slice( 1 ); const [ hours, mins, secs ] = [ seconds / 3600, seconds % 3600 / 60, seconds % 3600 % 60 ].map( ( x ) => String( Math.floor( x ) ).padStart( 2, '0' ) ); if ( hours === '00' && mins === '00' ) { return secs + fraction; } else if ( hours === '00' ) { return [ mins, secs + fraction ].join( ':' ); } else { return [ hours, mins, secs + fraction ].join( ':' ); } }; console.log(seconds2duration(25*3600 + 0*60 + 41 + 0.333, 0)); // 25:00:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 0)); // 05:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 1)); // 05:41.3 console.log(seconds2duration(0*3600 + 0*60 + 41 + 0.333, 2)); // 41.33

下面是将秒转换为hh-mm-ss格式的代码:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

在JavaScript中获得从将秒转换为HH-MM-SS格式的替代方法

您可以使用ES6生成器创建高度可定制的时间字符串。

下面是将数字从给定比例转换为数组的通用函数:

函数toScaledArray (n,尺度){ 函数* g(x, n=0){ 如果(x > 0) { 产生x %(尺度[n] | |∞); 产量* g (Math.floor (x /鳞片[n]), n + 1) } } 返回g (n)[…] } console.log (toScaledArray (6 (10,10))) console.log (toScaledArray(2000年,[30,12])) console.log (toScaledArray(45000年,[12]24日30日))

因此,我们可以使用它来创建时间字符串,如下所示:

> toScaledArray(45000,[60,60]).reverse().join(":")
< '12:30:0'
> toScaledArray(1234,[60,60]).reverse().join(":")
< '20:34'

函数也可以写成一行:

[...(function* g(x,n=0,scales=[60,60]){if(x>0) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().join("-")

上面的函数将省略前导零,如果你想将字符串精确地转换为'HH-MM-SS',你可以使用

[...(function* g(x,n=0,scales=[60,60]){if(x>0||n<3) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().map(x=>String(x).padStart(2, '0')).join("-")

此外,如果你需要的是'[H:]MM:SS',这里我们有:

Number.prototype.toTimeString = function(){ 返回[…(*函数g (x, n = 0,鳞片= (60 60)){if (x > 0 | | n < 2){收益率x %(尺度[n] | |∞);产量* g (Math.floor (x /鳞片[n]), n + 1,尺度)}})(这)]. map ((x, n) = > n < 2 ?字符串(x) .padStart (2, ' 0 '): x) .reverse () . join(“:”) } console.log (12 (12) .toTimeString ()) console.log (345, (345) .toTimeString ()) console.log (6789, (6789) .toTimeString ())

你也可以有D(ay),甚至M(onth)和Y(ear)(虽然不准确),如下所示:

> toScaledArray(123456789,[60,60,24,30,12]).map((x,n)=>n<2?String(x).padStart(2,'0'):x).reverse().join(":")
< '3:11:18:21:33:09'

这里输出的意思是“3年11个月18天21小时33分9秒”

总之,这是一种高度可定制的将数字转换为可缩放数组的方法,可用于时间字符串转换、人类可读的字节转换甚至纸币的更改。

对于任何使用AngularJS的人来说,一个简单的解决方案是使用date API来过滤值,它会根据请求的格式将毫秒转换为字符串。例子:

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

请注意,这需要毫秒,所以如果从秒转换(就像最初的问题一样),可能需要将timerremain乘以1000。

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.
    }
}