用JavaScript将秒转换为HH-MM-SS?

394

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


3
请看我在https://dev59.com/JG015IYBdhLWcg3w7wMW#6313008的回答。 - powtac
38个回答

1
对于使用AngularJS的人,一个简单的解决方案是使用date API过滤值,根据所请求的格式将毫秒转换为字符串。例如:
<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

注意,这里期望的是毫秒,所以如果你要从秒转换(就像原来的问题一样),你可能需要将timeRemaining乘以1000。

1

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

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


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

// For Example :
alert("186".toHHMMSS());


0
当我想象一个时钟或计时器时,我会像下面所示的那样:
const secondsTo_HHMMSS = (seconds) => {
      //format to a readable friendly timer
      let hour = Math.floor(seconds / 3600);
      let minute = Math.floor((seconds % 3600) / 60);
      let second = seconds % 60;

      if(hour.toString().length === 1) {
            hour = `0${hour}`;
      }
      if(minute.toString().length === 1) {
            minute = `0${minute}`;
      }
      if(second.toString().length === 1) {
            second = `0${second}`;
      };

      let timer = `${hour}-${minute}-${second}`;

      return timer;
}

0
一个不错的选择是使用Intl.DateTimeFormat。例如:
const timeFormat = new Intl.DateTimeFormat('es-US', {
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    hour12: false,
    timeZone: 'UTC'
});

const endTimeFormatted = timeFormat.format(new Date(SECS * 1000); //hour in secs

0

虽然这是相当简单的任务,但你们中的一些人直接推荐了 Moment.js,或编写了一些最丑陋的函数来解析一些秒数...

transform(time: number): string {
    if (time != null) {
        const hours: number = Math.floor(time / 3600);
        const minutes: number = Math.floor((time - (hours * 3600)) / 60);
        const seconds: number = time - (hours * 3600) - (minutes * 60);
        return [hours, (minutes < 10) ? '0' + minutes : minutes, (seconds < 10) ? '0' + seconds : seconds].join(':');
    } else {
        return '00:00:00';
    }
}

这将在任何情况下都能正常工作...


-2

你还可以使用Sugar

Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');

这个例子返回 '03:00'。


听起来不错!检查后发现它并没有返回03:00,而是对于任何输入的值都只返回00:00。 - Ben
他们可能已经更改了他们的API。我已经更新了代码(虽然有点晚,你可能已经转移了注意力,但我认为其他人可能会发现它有用)。 - Kris Khaira

-4

我以前使用过这段代码来创建一个简单的时间段对象:

function TimeSpan(time) {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;

while(time >= 3600)
{
    this.hours++;
    time -= 3600;
}

while(time >= 60)
{
    this.minutes++;
    time -= 60;
}

this.seconds = time;
}

var timespan = new Timespan(3662);

2
循环结果是一种非常糟糕的编码技术,永远不应该使用它会占用您的处理能力并使您的网站变得缓慢。 - yan bellavance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接