我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)

我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。

那么有一个小片段,这是在jQuery或只是原始JavaScript?


在谷歌上搜索的结果是这样的:

function secondsToTime(secs)
{
    secs = Math.round(secs);
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}

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("5678".toHHMMSS());

工作代码片段:

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; } console.log("5678".toHHMMSS());


我推荐使用普通的javascript,使用Date对象。(要获得更简短的解决方案,请使用toTimeString,请参阅第二个代码片段。)

var seconds = 9999;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);

(当然,创建的Date对象将有一个与之关联的实际日期,但该数据是无关的,因此出于这些目的,您不必担心它。)


编辑(简短的解决方案):

使用toTimeString函数并对空白进行分割:

var seconds = 9999; // Some arbitrary value
var date = new Date(seconds * 1000); // multiply by 1000 because Date() requires miliseconds
var timeStr = date.toTimeString().split(' ')[0];

toTimeString给出'16:54:58 GMT-0800 (PST)',对第一个空格进行分割给出'16:54:58'。


主题的变奏。处理个位数秒的方式有点不同

seconds2time(0)  ->  "0s" 
seconds2time(59) -> "59s" 
seconds2time(60) -> "1:00" 
seconds2time(1000) -> "16:40" 
seconds2time(4000) -> "1:06:40"

function seconds2time (seconds) {
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var time = "";

    if (hours != 0) {
      time = hours+":";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
      time += minutes+":";
    }
    if (time === "") {
      time = seconds+"s";
    }
    else {
      time += (seconds < 10) ? "0"+seconds : String(seconds);
    }
    return time;
}

正则表达式可以用来匹配Date对象的toString()方法返回的字符串中的时间子字符串,该字符串的格式如下:“Thu Jul 05 2012 02:45:12 GMT+0100 (GMT夏令时)”。请注意,此解决方案使用自epoch以来的时间:1970年1月1日午夜。这个解决方案可以是一行代码,不过将其拆分会更容易理解。

function secondsToTime(seconds) {
    const start = new Date(1970, 1, 1, 0, 0, 0, 0).getTime();
    const end = new Date(1970, 1, 1, 0, 0, parseInt(seconds), 0).getTime();
    const duration = end - start;

    return new Date(duration).toString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

要获得格式为hh:MM:ss的时间部分,可以使用下面的正则表达式:

(上面有人在同一篇文章中提到了这一点,谢谢。)

var替换= new日期().toTimeString () .replace (/ . * (\ d {2}: \ d {2}: \ d{2})。* / " $ 1 "); console.log(替换)


我喜欢第一个答案。 这里有一些优化:

源数据是一个数字。不需要额外的计算。 过多的计算

结果代码:

Number.prototype.toHHMMSS = function () {
    var seconds = Math.floor(this),
        hours = Math.floor(seconds / 3600);
    seconds -= hours*3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes*60;

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

这是另一个版本,也处理天数:

function FormatSecondsAsDurationString( seconds )
{
    var s = "";

    var days = Math.floor( ( seconds / 3600 ) / 24 );
    if ( days >= 1 )
    {
        s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
        seconds -= days * 24 * 3600;
    }

    var hours = Math.floor( seconds / 3600 );
    s += GetPaddedIntString( hours.toString(), 2 ) + ":";
    seconds -= hours * 3600;

    var minutes = Math.floor( seconds / 60 );
    s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
    seconds -= minutes * 60;

    s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );

    return s;
}

function GetPaddedIntString( n, numDigits )
{
    var nPadded = n;
    for ( ; nPadded.length < numDigits ; )
    {
        nPadded = "0" + nPadded;
    }

    return nPadded;
}

我是这么做的

function timeFromSecs(seconds)
{
    return(
    Math.floor(seconds/86400)+'d :'+
    Math.floor(((seconds/86400)%1)*24)+'h : '+
    Math.floor(((seconds/3600)%1)*60)+'m : '+
    Math.round(((seconds/60)%1)*60)+'s');
}

timeFromSecs(22341938)将返回“258d 14h 5m 38s”


使用moment.js库:

function humanizeDuration(input, units ) { 
  // units is a string with possible values of y, M, w, d, h, m, s, ms
  var duration = moment().startOf('day').add(units, input),
    format = "";

  if(duration.hour() > 0){ format += "H [hours] "; }

  if(duration.minute() > 0){ format += "m [minutes] "; }

  format += " s [seconds]";

  return duration.format(format);
}

这允许您指定任何持续时间,无论是小时、分钟、秒、磨,并返回人类可读的版本。


新的日期().toString()。分割(" ")[4];

结果15:08:03


我不喜欢在JavaScript中为标准数据类型添加属性,所以我建议这样做:

/**
 * Format a duration in seconds to a human readable format using the notion
 * "h+:mm:ss", e.g. "4:40:78". Negative durations are preceeded by "-".
 *
 * @param t Duration in seconds
 * @return The formatted duration string
 */
var readableDuration = (function() {

    // Each unit is an object with a suffix s and divisor d
    var units = [
        {s: '', d: 1}, // Seconds
        {s: ':', d: 60}, // Minutes
        {s: ':', d: 60}, // Hours
    ];

    // Closure function
    return function(t) {
        t = parseInt(t); // In order to use modulus
        var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat
        for (i = 0; i < units.length; i++) {
            n = Math.floor(n / units[i].d); // Total number of this unit
            // Truncate e.g. 26h to 2h using modulus with next unit divisor
            if (i+1 < units.length) // Tweak substr with two digits
                trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit
            else
                trunc = n;
            out.unshift(''+ trunc + units[i].s); // Output
        }
        (t < 0) ? out.unshift('-') : null; // Handle negative durations
        return out.join('');
    };
})();

用法:

var str = readableDuration(3808); // "1:03:28"

我还创建了一个更通用的版本。主要的区别是它接受毫秒(这是JS中的标准时间单位),而输出格式使用空格。


我会给artem的答案投票,但我是一个新海报。我确实扩展了他的解决方案,虽然不是OP要求的如下

    t=(new Date()).toString().split(" ");
    timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);

得到

0410月16:31:28太平洋时间

这对我很有用……

但如果你从一个时间量开始,我会用两个函数;一个用于格式化和填充,一个用于计算:

function sec2hms(timect){

  if(timect=== undefined||timect==0||timect === null){return ''};
  //timect is seconds, NOT milliseconds
  var se=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var mi=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var hr = timect % 24; //the remainder after div by 24
  var dy = Math.floor(timect/24);
  return padify (se, mi, hr, dy);
}

function padify (se, mi, hr, dy){
  hr = hr<10?"0"+hr:hr;
  mi = mi<10?"0"+mi:mi;
  se = se<10?"0"+se:se;
  dy = dy>0?dy+"d ":"";
  return dy+hr+":"+mi+":"+se;
}

s2t=function (t){
  return parseInt(t/86400)+'d '+(new Date(t%86400*1000)).toUTCString().replace(/.*(\d{2}):(\d{2}):(\d{2}).*/, "$1h $2m $3s");
}

s2t(123456);

结果:

1d 10h 17m 36s

如果你知道你有多少秒,这就可以了。它还使用本机Date()对象。

function formattime(numberofseconds){    
    var zero = '0', hours, minutes, seconds, time;

    time = new Date(0, 0, 0, 0, 0, numberofseconds, 0);

    hh = time.getHours();
    mm = time.getMinutes();
    ss = time.getSeconds() 

    // Pad zero values to 00
    hh = (zero+hh).slice(-2);
    mm = (zero+mm).slice(-2);
    ss = (zero+ss).slice(-2);

    time = hh + ':' + mm + ':' + ss;
    return time; 
}

我认为这是目前为止最快的性能:

var t = 34236; // your seconds
var time = ('0'+Math.floor(t/3600) % 24).slice(-2)+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2)
//would output: 09:30:36

我是这样做的。它似乎工作得相当好,而且非常紧凑。(不过,它使用了很多三元操作符)

function formatTime(seconds) {
  var hh = Math.floor(seconds / 3600),
    mm = Math.floor(seconds / 60) % 60,
    ss = Math.floor(seconds) % 60;
  return (hh ? (hh < 10 ? "0" : "") + hh + ":" : "") + ((mm < 10) && hh ? "0" : "") + mm + ":" + (ss < 10 ? "0" : "") + ss
}

...对于格式化字符串…

String.prototype.toHHMMSS = function() {
  formatTime(parseInt(this, 10))
};

function toHHMMSS(seconds) {
    var h, m, s, result='';
    // HOURs
    h = Math.floor(seconds/3600);
    seconds -= h*3600;
    if(h){
        result = h<10 ? '0'+h+':' : h+':';
    }
    // MINUTEs
    m = Math.floor(seconds/60);
    seconds -= m*60;
    result += m<10 ? '0'+m+':' : m+':';
    // SECONDs
    s=seconds%60;
    result += s<10 ? '0'+s : s;
    return result;
}

例子

    toHHMMSS(111); 
    "01:51"

    toHHMMSS(4444);
    "01:14:04"

    toHHMMSS(33);
    "00:33"

你可以在没有任何外部JS库的帮助下使用JS Date方法做到这一点,如下所示:

var date = new date (0); date.setSeconds (45);//指定SECONDS的值 var timeString = date.toISOString()。substring(11、19); console.log (timeString)


毫秒到持续时间,简单的方法是:

// To have leading zero digits in strings.
function pad(num, size) {
    var s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
}

// ms to time/duration
msToDuration = function(ms){
    var seconds = ms / 1000;
    var hh = Math.floor(seconds / 3600),
    mm = Math.floor(seconds / 60) % 60,
    ss = Math.floor(seconds) % 60,
    mss = ms % 1000;
    return pad(hh,2)+':'+pad(mm,2)+':'+pad(ss,2)+'.'+pad(mss,3);
}

它将327577转换为00:05:27.577。

更新

另一种不同场景的方法:

toHHMMSS = function (n) {
    var sep = ':',
        n = parseFloat(n),
        sss = parseInt((n % 1)*1000),
        hh = parseInt(n / 3600);
    n %= 3600;
    var mm = parseInt(n / 60),
        ss = parseInt(n % 60);
    return pad(hh,2)+sep+pad(mm,2)+sep+pad(ss,2)+'.'+pad(sss,3);
    function pad(num, size) {
        var str = num + "";
        while (str.length < size) str = "0" + str;
        return str;
    }
}

toHHMMSS(6315.077) // Return 01:45:15.077

toHHMMSS的非原型版本:

    function toHHMMSS(seconds) {
        var sec_num = parseInt(seconds);
        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;}
        var time    = hours+':'+minutes+':'+seconds;
        return time;
    }   

我喜欢Powtac的答案,但我想在angular.js中使用它,所以我用他的代码创建了一个过滤器。

.filter('HHMMSS', ['$filter', function ($filter) {
    return function (input, decimals) {
        var sec_num = parseInt(input, 10),
            decimal = parseFloat(input) - sec_num,
            hours   = Math.floor(sec_num / 3600),
            minutes = Math.floor((sec_num - (hours * 3600)) / 60),
            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;}
        var time    = hours+':'+minutes+':'+seconds;
        if (decimals > 0) {
            time += '.' + $filter('number')(decimal, decimals).substr(2);
        }
        return time;
    };
}])

它在功能上是相同的,除了我添加了一个可选的小数字段来显示小数秒。像使用其他过滤器一样使用它:

{{elapsedTime | HHMMSS}}显示:01:23:45

{{elapsedTime | HHMMSS: 3}}显示:01:23:45.678


我最喜欢Webjins的答案,所以我扩展了它以显示d后缀的日子,使显示有条件,并包括一个s后缀的普通秒:

function sec2str(t){
    var d = Math.floor(t/86400),
        h = ('0'+Math.floor(t/3600) % 24).slice(-2),
        m = ('0'+Math.floor(t/60)%60).slice(-2),
        s = ('0' + t % 60).slice(-2);
    return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
}

返回"3d 16:32:12"或"16:32:12"或"32:12"或"12s"


我个人更喜欢不带前导零的开头单位(天、小时、分钟)。但是秒应该总是以分钟(0:13)开头,这种表示很容易被认为是“持续时间”,不需要进一步解释(标记为min, sec(s)等),可用于各种语言(国际化)。

    // returns  (-)d.h:mm:ss(.f)
    //          (-)h:mm:ss(.f)
    //          (-)m:ss(.f)
    function formatSeconds (value, fracDigits) {
        var isNegative = false;
        if (isNaN(value)) {
            return value;
        } else if (value < 0) {
            isNegative = true;
            value = Math.abs(value);
        }
        var days = Math.floor(value / 86400);
        value %= 86400;
        var hours = Math.floor(value / 3600);
        value %= 3600;
        var minutes = Math.floor(value / 60);
        var seconds = (value % 60).toFixed(fracDigits || 0);
        if (seconds < 10) {
            seconds = '0' + seconds;
        }

        var res = hours ? (hours + ':' + ('0' + minutes).slice(-2) + ':' + seconds) : (minutes + ':' + seconds);
        if (days) {
            res = days + '.' + res;
        }
        return (isNegative ? ('-' + res) : res);
    }

//模仿服务器端(.net, c#)持续时间格式:

    public static string Format(this TimeSpan interval)
    {
        string pattern;
        if (interval.Days > 0)          pattern = @"d\.h\:mm\:ss";
        else if (interval.Hours > 0)    pattern = @"h\:mm\:ss";
        else                            pattern = @"m\:ss";
        return string.Format("{0}", interval.ToString(pattern));
    }

这很简单,

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

以下是我的解决方案。您可以尝试下面的代码片段。

函数secToHHMM(sec) { var d = new Date(); d.setHours (0); d.setMinutes (0); d.setSeconds (0); d = new Date(d.getTime() + sec*1000); 返回d.toLocaleString (en)。分割(' ')[1]; }; alert('One hour: ' + secToHHMM(60*60));/ /“01:00:00” alert(' 1小时5分钟:' + secToHHMM(60*60 + 5*60));/ /“01:05:00” alert(' 1小时5分23秒:' + secToHHMM(60*60 + 5*60 + 23));/ /“01:05:23”


如果你是在处理视频长度,这个版本的公认答案会让它看起来更漂亮:

1:37:40(1小时/ 37分钟/ 40秒)

1:00(1分钟)

2:20(2分20秒)

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

  var hourSeparator = ':';
  var minuteSeparator = ':';

  if(hours == 0){hours = '';hourSeparator = '';}
  if (minutes < 10 && hours != 0) {minutes = "0"+minutes;}
  if (seconds < 10) {seconds = "0"+seconds;}
  var time = hours+hourSeparator+minutes+minuteSeparator+seconds;
  return time;
}

以下是我的看法:

function formatTime(seconds) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.round(seconds % 60);
  return [
    h,
    m > 9 ? m : (h ? '0' + m : m || '0'),
    s > 9 ? s : '0' + s
  ].filter(Boolean).join(':');
}

预期结果:

const expect = require('expect');
expect(formatTime(0)).toEqual('0:00');
expect(formatTime(1)).toEqual('0:01');
expect(formatTime(599)).toEqual('9:59');
expect(formatTime(600)).toEqual('10:00');
expect(formatTime(3600)).toEqual('1:00:00');
expect(formatTime(360009)).toEqual('100:00:09');
expect(formatTime(0.2)).toEqual('0:00');

            //secondsToTime();
            var t = wachttijd_sec; // your seconds
            var hour = Math.floor(t/3600);
            if(hour < 10){
                hour = '0'+hour;
            }
            var time = hour+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2);
            //would output: 00:00:00 > +100:00:00

即使超过24小时也能保持倒计时


可以使用以下函数将时间转换为HH:MM:SS格式:

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

Demo

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 : ':' ); } document.body.innerHTML = '<pre>' + JSON.stringify({ 5.3515555 : convertTime(5.3515555), 126.2344452 : convertTime(126.2344452, '-'), 1156.1535548 : convertTime(1156.1535548, '.'), 9178.1351559 : convertTime(9178.1351559, ':'), 13555.3515135 : convertTime(13555.3515135, ',') }, null, '\t') + '</pre>';

看看这小提琴。


function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}

你可以使用moment .js的moment-duration-format插件:

Var秒= 3820; Var duration =时刻。持续时间(秒,“秒”); Var format = duration.format("hh:mm:ss"); console.log(格式化);/ / 01:03:40 <!——Moment.js库——> .js库 < script src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js " > < /脚本> <!——moment-duration-format插件——> < script src = " https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js " > < /脚本>

看看这把小提琴


function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    if(hours >= 12)
    {
     var m= 'pm' ;
     }
     else
     {
         var m='am'
     }
     if(hours-12 >0)
     {
            var hrs = hours-12;
     }
     else if(hours-12 <0)
     {
            var hrs = hours;
     }
    var obj = {
        "h": hrs,
        "m": minutes,
        "s": seconds,
        "a":m
    };


    return obj;
}
var d = new Date();
var n = d.getHours();
var hms = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();   // your input string
var a = hms.split(':'); // split it at the colons

// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 




console.log(seconds);
console.log(secondsToTime(seconds))

https://jsfiddle.net/jithinksoft/9x6z4sdt/


块上的字符串有一个新方法:padStart

const str = '5';
str.padStart(2, '0'); // 05

下面是一个示例用例:用4行JavaScript编写YouTube持续时间


const secondsToTime = (seconds, locale) => { const date = new date (0); 日期。setHours(0, 0, seconds, 0); 返回date.toLocaleTimeString(地区); } “en”console.log (secondsToTime (3610));

在哪里区域参数(“en”,“de”等)是可选的


/**
 * Formats seconds (number) to H:i:s format.
 * 00:12:00
 *
 * When "short" option is set to true, will return:
 * 0:50
 * 2:00
 * 12:00
 * 1:00:24
 * 10:00:00
 */
export default function formatTimeHIS (seconds, { short = false } = {}) {
  const pad = num => num < 10 ? `0${num}` : num

  const H = pad(Math.floor(seconds / 3600))
  const i = pad(Math.floor(seconds % 3600 / 60))
  const s = pad(seconds % 60)

  if (short) {
    let result = ''
    if (H > 0) result += `${+H}:`
    result += `${H > 0 ? i : +i}:${s}`
    return result
  } else {
    return `${H}:${i}:${s}`
  }
}

secToHHMM(number: number) {
    debugger;
    let hours = Math.floor(number / 3600);
    let minutes = Math.floor((number - (hours * 3600)) / 60);
    let seconds = number - (hours * 3600) - (minutes * 60);
    let H, M, S;
    if (hours < 10) H = ("0" + hours);
    if (minutes < 10) M = ("0" + minutes);
    if (seconds < 10) S = ("0" + seconds);
    return (H || hours) + ':' + (M || minutes) + ':' + (S || seconds);
}

下面是它的es6版本:

export const parseTime = (time) => { // send time in seconds
// eslint-disable-next-line 
let hours = parseInt(time / 60 / 60), mins = Math.abs(parseInt(time / 60) - (hours * 60)), seconds = Math.round(time % 60);
return isNaN(hours) || isNaN(mins) || isNaN(seconds) ? `00:00:00` : `${hours > 9 ? Math.max(hours, 0) : '0' + Math.max(hours, 0)}:${mins > 9 ? Math.max(mins, 0) : '0' + Math.max(0, mins)}:${seconds > 9 ? Math.max(0, seconds) : '0' + Math.max(0, seconds)}`;}

以下是2019年更新的一句话:

//your date
var someDate = new Date("Wed Jun 26 2019 09:38:02 GMT+0100") 

var result = `${String(someDate.getHours()).padStart(2,"0")}:${String(someDate.getMinutes()).padStart(2,"0")}:${String(someDate.getSeconds()).padStart(2,"0")}`

//result will be "09:38:02"

我看到每个人都在发布他们对这个问题的看法,尽管事实上很少有顶级答案已经包含了针对特定用例定制的所有必要信息。

既然我也想赶时髦——下面是我不必要的、有点麻烦的解决方案,那就是:

a)可读性强(希望如此!) b)易于定制 c)不打印任何零

滚筒滚

function durationToDDHHMMSSMS(durms) {
    if (!durms) return "??";

    var HHMMSSMS = new Date(durms).toISOString().substr(11, 12);
    if (!HHMMSSMS) return "??";

    var HHMMSS = HHMMSSMS.split(".")[0];
    if (!HHMMSS) return "??";

    var MS = parseInt(HHMMSSMS.split(".")[1],10);
    var split = HHMMSS.split(":");
    var SS = parseInt(split[2],10);
    var MM = parseInt(split[1],10);
    var HH = parseInt(split[0],10); 
    var DD = Math.floor(durms/(1000*60*60*24));

    var string = "";
    if (DD) string += ` ${DD}d`;
    if (HH) string += ` ${HH}h`;
    if (MM) string += ` ${MM}m`;
    if (SS) string += ` ${SS}s`;
    if (MS) string += ` ${MS}ms`;

    return string;
},

注意,这段代码使用ES6模板字符串,我相信像你这样聪明的人在需要时用常规字符串替换它们没有困难。


这里有一个相当简单的解决方案,四舍五入到最近的秒!

var returnElapsedTime =函数(epoch) { //我们假设epoch以秒为单位 Var小时= epoch / 3600, 分钟=(小时% 1)* 60, 秒=(分钟% 1)* 60; 返回Math.floor(小时)+ ":" + Math.floor(分钟)+ ":" + Math.round(秒); }


这是我最近为MM:SS写的。它不完全符合问题,但它是一种不同的单行格式。

const time = 60 * 2 + 35; // 2 minutes, 35 seconds
const str = (~~(time / 60) + "").padStart(2, '0') + ":" + (~~((time / 60) % 1 * 60) + "").padStart(2, '0');

str // 02:35

编辑:添加这个是为了多样化,但这里最好的解决方案是下面的https://stackoverflow.com/a/25279399/639679。


这是最简单的方法。

new Date(sec * 1000).toISOString().substr(11, 8)

最普遍的答案是

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
      r => [r]
    )(seconds)
    .map(a => a.toString().padStart(2, '0'))
    .join(':');
}

一些示例输出:

> hms(0)
< "00:00:00"

> hms(5)
< "00:00:05"

> hms(60)
< "00:01:00"

> hms(3785)
< "01:03:05"

> hms(37850)
< "10:30:50"

> hms(378500)
< "105:08:20"

详见https://stackoverflow.com/a/66504936/1310733


下面是一个使用Date.prototype.toLocaleTimeString()的例子。我选择GB作为语言,因为美国在最初的小时显示的是24而不是00。此外,我选择Etc/UTC作为时区,因为UTC在tz数据库时区列表中是它的别名。

const formatTime = (seconds) => 新日期(秒* 1000)。toLocaleTimeString(“en”{ 时区:“等/ UTC ', hour12:假的, 小时:“便是”, 分钟:“便是”, 第二:“便是” }); console.log (formatTime (75));/ / 00:01:15 .as-console-wrapper {top: 0;Max-height: 100%重要;}

下面是相同的示例,但是使用了Intl.DateTimeFormat。这个变体允许您实例化一个可重用的格式化器对象,这更具有性能。

const dateFormatter = new Intl。DateTimeFormat(“en”{ 时区:“等/ UTC ', hour12:假的, 小时:“便是”, 分钟:“便是”, 第二:“便是” }); const formatTime = (seconds) => dateFormatter。format(new Date(seconds * 1000)); console.log (formatTime (75));/ / 00:01:15 .as-console-wrapper {top: 0;Max-height: 100%重要;}


function secToTime(seconds, separator) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ].join(separator ? separator : ':')
    .replace(/\b(\d)\b/g, "0$1").replace(/^00\:/,'')
}

你现在可以这样使用它:

alert(secToTime("123"));

工作代码片段:

函数secToTime(秒,分隔符){ 返回( parseInt(seconds / 60 / 60), parseInt(seconds / 60% 60), parseInt(seconds % 60) ]。加入(分离器?分隔符:':') .replace (/ \ b \ b / g (\ d),“0 1美元”).replace(/ ^ 00 \: /,”) } console.log (secToTime (" 123 "));


以下是@meiyang的优秀解决方案的一个变体,我最终使用了它:

    function duration(seconds) {
        return [
            format(seconds / 60 / 60),
            format(seconds / 60 % 60),
            format(seconds % 60)
        ].join(':');
    }

    format(n) {
        return (~~n).toString().padStart(2, '0')
    }

PS:同样值得注意的是,上面的一些其他解决方案只适用于< 24h的值