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

发布于 2024-11-15 02:10:53 字数 142 浏览 4 评论 0原文

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

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

那么是否有一个小片段可以在 jQuery 或原始 JavaScript 中执行此操作?

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about converting to x hours and x minutes format.

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

拧巴小姐 2024-11-22 02:10:54

您可以借助 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)

You can manage to do this without any external JS library with the help of JS Date method like following:

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

自控 2024-11-22 02:10:54

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

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

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

To get the time part in the format hh:MM:ss, you can use this regular expression:

(This was mentioned above in same post by someone, thanks for that.)

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

冷夜 2024-11-22 02:10:54

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

I recommend ordinary javascript, using the Date object. (For a shorter solution, using toTimeString, see the second code snippet.)

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

(Of course, the Date object created will have an actual date associated with it, but that data is extraneous, so for these purposes, you don't have to worry about it.)


Edit (short solution):

Make use of the toTimeString function and split on the whitespace:

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 gives '16:54:58 GMT-0800 (PST)', and splitting on the first whitespace gives '16:54:58'.

姜生凉生 2024-11-22 02:10:54

这是我的看法:

function formatTime(ms: number) {
  const seconds = Math.floor(Math.abs(ms / 1000))
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.round(seconds % 60)
  const t = [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
    .filter(Boolean)
    .join(':')
  return ms < 0 && seconds ? `-${t}` : t
}

预期结果:

import assert from 'assert'
assert.equal(formatTime(0), '0:00')
assert.equal(formatTime(1_000), '0:01')
assert.equal(formatTime(599_000), '9:59')
assert.equal(formatTime(600_000), '10:00')
assert.equal(formatTime(3600_000), '1:00:00')
assert.equal(formatTime(360009_000), '100:00:09')
assert.equal(formatTime(200), '0:00')
assert.equal(formatTime(-200), '0:00')
assert.equal(formatTime(-1_000), '-0:01')

Here's my take on it:

function formatTime(ms: number) {
  const seconds = Math.floor(Math.abs(ms / 1000))
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.round(seconds % 60)
  const t = [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
    .filter(Boolean)
    .join(':')
  return ms < 0 && seconds ? `-${t}` : t
}

Expected results:

import assert from 'assert'
assert.equal(formatTime(0), '0:00')
assert.equal(formatTime(1_000), '0:01')
assert.equal(formatTime(599_000), '9:59')
assert.equal(formatTime(600_000), '10:00')
assert.equal(formatTime(3600_000), '1:00:00')
assert.equal(formatTime(360009_000), '100:00:09')
assert.equal(formatTime(200), '0:00')
assert.equal(formatTime(-200), '0:00')
assert.equal(formatTime(-1_000), '-0:01')
神经暖 2024-11-22 02:10:54

Google 搜索出现了此结果

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

A Google search turned up this result:

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;
}
待天淡蓝洁白时 2024-11-22 02:10:54
function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}
function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}
戴着白色围巾的女孩 2024-11-22 02:10:54

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

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

Variation on a theme. Handles single digit seconds a little differently

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;
}
囚我心虐我身 2024-11-22 02:10:54

使用令人惊叹的 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);
}

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

Using the amazing moment.js library:

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

This allows you to specify any duration be it hours, minutes, seconds, mills, and returns a human readable version.

浪推晚风 2024-11-22 02:10:54

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

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

  • 超额计算

结果代码:

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

I like the first answer.
There some optimisations:

  • source data is a Number. additional calculations is not needed.

  • much excess computing

Result code:

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;
}
同展鸳鸯锦 2024-11-22 02:10:54

以下是使用 Date 的示例。原型.toLocaleTimeString()。我选择 GB 作为语言,因为美国在初始小时显示 24 而不是 00。此外,我选择 Etc/UTC 作为时区,因为 UTCtz 数据库时区列表

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

Here is an example of using Date.prototype.toLocaleTimeString(). I chose GB as the language, because the US shows a 24 instead of a 00 for the initial hour. Furthermore, I chose Etc/UTC as the time zone, because UTC is aliased to it in the list of tz database time zones.

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

Here is the same example, but with Intl.DateTimeFormat. This variant lets you instantiate a reusable formatter object, which is more performant.

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

海夕 2024-11-22 02:10:54

这很容易,

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

It's pretty easy,

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
放肆 2024-11-22 02:10:54

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

结果 15:08:03

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

result 15:08:03

伪心 2024-11-22 02:10:54

最简单的方法。

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

Easiest way to do it.

new Date(sec * 1000).toISOString().substr(11, 8)
↘紸啶 2024-11-22 02:10:54
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
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);

result:

1d 10h 17m 36s
朕就是辣么酷 2024-11-22 02:10:54

我最喜欢 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');
}

返回“3d 16:32:12”或“16:32:12”或“32: 12 英寸或“12 秒”

I liked Webjins answer the most, so i extended it to display days with a d suffix, made display conditional and included a s suffix on plain seconds:

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

returns "3d 16:32:12" or "16:32:12" or "32:12" or "12s"

郁金香雨 2024-11-22 02:10:54

我喜欢 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 }} 显示: 01:23:45 {{ elapsedTime | HHMMSS HHMMSS : 3 }} 显示: 01:23:45.678

I loved Powtac's answer, but I wanted to use it in angular.js, so I created a filter using his code.

.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;
    };
}])

It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

{{ elapsedTime | HHMMSS }} displays: 01:23:45

{{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678

过度放纵 2024-11-22 02:10:54

对此最常见的答案是

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

The most general answer to this is

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(':');
}

Some example outputs:

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

See explanation at https://stackoverflow.com/a/66504936/1310733

层林尽染 2024-11-22 02:10:54

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

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

Here is yet another version, which handles days also:

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;
}
柒七 2024-11-22 02:10:54
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"
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;
}

Examples

    toHHMMSS(111); 
    "01:51"

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

    toHHMMSS(33);
    "00:33"
_畞蕅 2024-11-22 02:10:54
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"));

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\:/,'')
}

You can use it now like:

alert(secToTime("123"));

Working snippet:

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

戴着白色围巾的女孩 2024-11-22 02:10:54

我认为就性能而言,这是迄今为止最快的:

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

I think performance wise this is by far the fastest:

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
影子是时光的心 2024-11-22 02:10:54

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

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

Here's how I did it. It seems to work fairly well, and it's extremely compact. (It uses a lot of ternary operators, though)

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
}

...and for formatting strings...

String.prototype.toHHMMSS = function() {
  formatTime(parseInt(this, 10))
};
记忆消瘦 2024-11-22 02:10:54

您可以使用以下函数将时间(以秒为单位)转换为 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>';

另请参阅此小提琴

You can use the following function to convert time (in seconds) to HH:MM:SS format :

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

Without passing a separator, it uses : as the (default) separator :

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

If you want to use - as a separator, just pass it as the second parameter:

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

See also this Fiddle.

揪着可爱 2024-11-22 02:10:54

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

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

这是一个示例用例:4 行 JavaScript 中的 YouTube 时长

There's a new method for strings on the block: padStart

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

Here is a sample use case: YouTube durations in 4 lines of JavaScript

与之呼应 2024-11-22 02:10:54

可以使用正则表达式来匹配 Date 对象的 toString() 方法返回的字符串中的时间子字符串,其格式如下:“Thu 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");
}

A regular expression can be used to match the time substring in the string returned from the toString() method of the Date object, which is formatted as follows: "Thu Jul 05 2012 02:45:12 GMT+0100 (GMT Daylight Time)". Note that this solution uses the time since the epoch: midnight of January 1, 1970. This solution can be a one-liner, though splitting it up makes it much easier to understand.

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");
}
╭⌒浅淡时光〆 2024-11-22 02:10:54

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

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

Here is a fairly simple solution that rounds to the nearest second!

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

唔猫 2024-11-22 02:10:54

这是我最近为 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 下面。

This is one I wrote recently for MM:SS. It's not exact to the question, but it's a different one-liner format.

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

Edit: This was added for variety, but the best solution here is https://stackoverflow.com/a/25279399/639679 below.

找回味觉 2024-11-22 02:10:54

这就是我的做法

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'

This is how i did it

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) will return '258d 14h 5m 38s'

悍妇囚夫 2024-11-22 02:10:54

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

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

I'm personally prefer the leading unit (days, hours, minutes) without leading zeros. But seconds should always be leaded by minutes (0:13), this presentation is easily considered as 'duration', without further explanation (marking as min, sec(s), etc.), usable in various languages (internationalization).

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

//imitating the server side (.net, C#) duration formatting like:

    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));
    }
梨涡 2024-11-22 02:10:53
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());

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

You can use it now like:

alert("5678".toHHMMSS());

Working snippet:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文