JavaScript 秒到时间字符串,格式为 hh:mm:ss

JavaScript seconds to time string with format hh:mm:ss

本文关键字:hh mm ss 格式 时间 字符串 JavaScript      更新时间:2023-09-26

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

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

那么有没有一个小片段在jQuery中或只是原始JavaScript中做到这一点?

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

借助 JS Date 方法,您可以在没有任何外部 JS 库的情况下设法做到这一点,如下所示:

var date = new Date(0);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substring(11, 19);
console.log(timeString)

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

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

    var myDate = new Date().toTimeString().replace(/.*('d{2}:'d{2}:'d{2}).*/, "$1");
    console.log(myDate)

我推荐普通的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'

以下是我对它的看法:

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

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

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

主题的变体。处理个位数秒数略有不同

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;
}
function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/'b('d)'b/g, "0$1")
}

利用惊人的时刻.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);
}

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

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

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

  • 多余计算

结果代码:

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 toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/('d'd:'d'd:'d'd)/)[0];
}

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

结果15:08:03

最简单的方法。

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

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

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
.as-console-wrapper { top: 0; max-height: 100% !important; }

这是相同的示例,但带有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
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

我最喜欢 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">

我喜欢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

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

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

例子

    到HHMMSS(111(;    '"01:51'"    到HHMMSS(4444(;    '"01:14:04'"    到HHMMSS(33(;    '"00:33'">

对此最普遍的答案是

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 中的解释

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

工作片段:

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':/,'')
}
console.log(secToTime("123"));

我认为在性能方面,这是迄今为止最快的:

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))
};
您可以使用

以下函数将时间(以秒为单位(转换为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
<小时 />

演示

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

另请参阅此小提琴

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

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

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

const secondsToTime = (seconds, locale) => {
    const date = new Date(0);
    date.setHours(0, 0, seconds, 0);
    return date.toLocaleTimeString(locale);
}
console.log(secondsToTime(3610, "en"));

其中区域设置参数("en"、"de"等(是可选的

则表达式可用于匹配从 Date 对象的 toString() 方法返回的字符串中的时间子字符串,其格式如下:"星期四 Jul 05 2012 02:45:12 GMT+0100 (GMT 夏令时("。请注意,此解决方案使用自纪元以来的时间: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");
}

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

var returnElapsedTime = function(epoch) {
  //We are assuming that the epoch is in seconds
  var hours = epoch / 3600,
      minutes = (hours % 1) * 60,
      seconds = (minutes % 1) * 60;
  return Math.floor(hours) + ":" + Math.floor(minutes) + ":" + Math.round(seconds);
}

这是我

最近为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。

我就是这样做的

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'