使用格式hh:mm:ss的JavaScript秒到时间字符串

med*_*edk 272 javascript time date date-format time-format

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

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

那么有一个小代码片段可以用jQuery或原始JavaScript来完成吗?

pow*_*tac 542

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;
}
Run Code Online (Sandbox Code Playgroud)

您现在可以使用它:

alert("5678".toHHMMSS());
Run Code Online (Sandbox Code Playgroud)

工作片段:

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());
Run Code Online (Sandbox Code Playgroud)

  • 不要投入原型,只需制作实用功能. (44认同)
  • 使用"%"运算符>> var minutes = Math.floor((sec_num%3600)/ 60); var seconds = Math.floor(sec_num%60); (20认同)
  • 为这样的东西修改原型?390赞成?当真? (9认同)
  • 对于某些值,这将失败,并且秒数最终显示为 60。示例 00:14:60。对此解决方案获得如此高的投票数感到惊讶,但似乎没有人真正对其进行彻底测试。 (4认同)
  • 啊谢谢.在整数上调用.toString()之前,我没有看到它作为字符串双向工作.你可以通过解析int来使它工作相反 (3认同)

Har*_*chu 151

您可以使用JS Date方法在没有任何外部JS库的情况下执行此操作,如下所示:

var date = new Date(null);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substr(11, 8);
console.log(timeString)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案.它可以更短:`new Date(1000*seconds).toISOString().substr(11,8)`. (22认同)
  • 如果持续时间长于 23:59:59,则会中断。 (12认同)
  • 很好的答案.您可以在`substr`之后使用`.replace(/ ^ [0:] + /,"")`从字符串的开头删除所有零和`:`. (4认同)
  • 为什么这个答案如此之低?我在2011年得到它可能IE 7和8是不支持它的基础,但它是2014年底,所以这个简单明了,无忧无虑的解决方案应该更高. (3认同)
  • 将其添加到前面以处理超过 24 小时的时间。parseInt(d / 86400) + "d " (3认同)
  • Bohumir 的评论,但没有弃用的 substr:`new Date(1000 * 秒).toISOString().substring(11, 19)` (3认同)
  • 来自 MDN:如果您指定的参数超出预期范围,则 setSeconds() 尝试相应地更新 Date 对象中的日期信息。例如,如果您将 100 用于 secondsValue,则存储在 Date 对象中的分钟将增加 1,而 40 将用于秒。所以是的,看起来不错! (2认同)
  • 很好的解决方案。为那些不知道的人添加这个明显的位:如果您只想要 mm:ss,那么您将 substr 更改为:`var timeString = date.toISOString().substr(14, 5);` (2认同)

小智 77

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

(上面有人在同一篇文章中提到过,谢谢你.)

    var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    console.log(myDate)
Run Code Online (Sandbox Code Playgroud)

  • +1 - 超级简单; 谢谢!只是使用了这个的变体来显示分钟和秒:`var myDate = new Date().toTimeString().replace(/.*(\ d {2}:\ d {2})(:\ d { 2}).*/,"$ 1");` (7认同)
  • 使用"替换"令人困惑.为什么不使用`new Date(null,null,null,null,null,timeInSeconds).toTimeString().match(/\d {2}:\ d {2}:\ d {2} /)[0]` ? (6认同)
  • 这对于显示给定时间是好的,但请注意问题(以及此处的其他答案)是关于显示持续时间,即与当前时间无关的给定秒数. (4认同)
  • 更简单的版本:`new Date().toTimeString().split("")[0]` (3认同)

Jel*_*Cat 50

我推荐普通的javascript,使用Date对象:

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);
Run Code Online (Sandbox Code Playgroud)

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

  • 如果我使用`date.getUTCHours()`和`date.getUTCMinutes()`,我得到一个正确的结果. (3认同)
  • 我喜欢这个,但它确实假设持续时间少于 24 小时 (3认同)
  • 时区讨厌这个。 (3认同)

Ash*_*nko 37

谷歌搜索出现了这个结果:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • `secondsToTime(119.9)`=>`对象{h:0,m:1,s:60}`.要解决此问题,请在方法开头添加`secs = Math.round(secs);`.当然,我们在演示期间看到了这个bug ... (8认同)

jot*_*tos 28

主题的变化.处理单个数字的秒数略有不同

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;
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*rez 20

这是我的看法:

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

预期成绩:

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');
Run Code Online (Sandbox Code Playgroud)

  • @RubenStolk 我觉得有一个需要两个“second”参数的函数有点令人困惑。我发现我的版本更清晰,即使它有点冗长。 (2认同)
  • 很好的解决方案。也许只需将秒更改为“const s = Math.round(seconds % 60);” (2认同)

Ser*_* K. 14

我喜欢第一个答案.有一些优化:

  • 源数据是一个数字.不需要额外的计算.

  • 多余的计算

结果代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 赞成的答案,就像这个一样,很糟糕。我敢打赌,您不需要所有数字都可以使用此方法。不要修改随机实用程序的原型。 (4认同)
  • 我认为`Number`是正确的,因为`seconds`实际上是一个数字.你应该在使用这个函数之前从string转换,这是正确的做法! (3认同)

Pra*_*eep 13

使用惊人的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);
}
Run Code Online (Sandbox Code Playgroud)

这允许您指定任何持续时间,包括小时,分钟,秒,铣削,并返回人类可读的版本.


小智 13

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

  • 非常自我解释和良好的答案,减少并简化了最佳答案。 (2认同)

Mr.*_*irl 13

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

const formatTime = (seconds) =>
  new Date(seconds * 1000).toLocaleTimeString('en-GB', {
    timeZone:'Etc/UTC',
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

console.log(formatTime(75)); // 00:01:15
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { top: 0; max-height: 100% !important; }
Run Code Online (Sandbox Code Playgroud)

这是相同的示例,但带有Intl.DateTimeFormat. 此变体允许您实例化可重用的格式化程序对象,该对象的性能更高。

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
  timeZone:'Etc/UTC',
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
});

const formatTime = (seconds) => dateFormatter.format(new Date(seconds * 1000));

console.log(formatTime(75)); // 00:01:15
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { top: 0; max-height: 100% !important; }
Run Code Online (Sandbox Code Playgroud)


Art*_*yba 10

new Date().toString().split(" ")[4];

结果 15:08:03


Hun*_* Vo 9

这很简单,

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


小智 8

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);
Run Code Online (Sandbox Code Playgroud)

结果:

1d 10h 17m 36s
Run Code Online (Sandbox Code Playgroud)


Arj*_*ava 8

最简单的方法。

new Date(sec * 1000).toISOString().substr(11, 8)
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,这是对 24 小时取模,因此如果您输入相当于 25 小时的时间,它将显示为 1 小时。当心 (3认同)

Mor*_*red 6

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

.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;
    };
}])
Run Code Online (Sandbox Code Playgroud)

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

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

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


nïk*_*ïkö 6

我喜欢Webjins的答案最多,所以我将它扩展到显示带有后缀的日期,使显示有条件并在简单秒中包含为后缀:

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');
}
Run Code Online (Sandbox Code Playgroud)

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