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


当前回答

这里有一个转换时间的简单函数,可能会有帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

其他回答

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

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

使用的例子

alert("186".toHHMMSS());

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

转换为持续时间(即,应适用于大于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

这个函数应该这样做:

var convertTime = function (input, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    return [
        pad(Math.floor(input / 3600)),
        pad(Math.floor(input % 3600 / 60)),
        pad(Math.floor(input % 60)),
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

在不传递分隔符的情况下,它使用:作为(默认)分隔符:

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

如果你想使用-作为分隔符,只需将其作为第二个参数传递:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

看看这小提琴。

您尝试过向Date对象添加秒数吗?

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);

一个示例: https://jsfiddle.net/j5g2p0dc/5/

更新: 样本链接缺失,所以我创建了一个新的。

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