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


当前回答

下面是将秒转换为hh-mm-ss格式的代码:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

在JavaScript中获得从将秒转换为HH-MM-SS格式的替代方法

其他回答

正如Cleiton在他的回答中指出的,moment.js可以用于:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

这里有一个转换时间的简单函数,可能会有帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

这是一个非常简单的任务,但你们中的一些人直接推荐了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';
    }
}

这在任何情况下都适用……

下面是一个函数,根据powtac的答案将秒转换为hh-mm-ss格式

斯菲德尔

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

示例使用

var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10

您可以使用ES6生成器创建高度可定制的时间字符串。

下面是将数字从给定比例转换为数组的通用函数:

函数toScaledArray (n,尺度){ 函数* g(x, n=0){ 如果(x > 0) { 产生x %(尺度[n] | |∞); 产量* g (Math.floor (x /鳞片[n]), n + 1) } } 返回g (n)[…] } console.log (toScaledArray (6 (10,10))) console.log (toScaledArray(2000年,[30,12])) console.log (toScaledArray(45000年,[12]24日30日))

因此,我们可以使用它来创建时间字符串,如下所示:

> toScaledArray(45000,[60,60]).reverse().join(":")
< '12:30:0'
> toScaledArray(1234,[60,60]).reverse().join(":")
< '20:34'

函数也可以写成一行:

[...(function* g(x,n=0,scales=[60,60]){if(x>0) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().join("-")

上面的函数将省略前导零,如果你想将字符串精确地转换为'HH-MM-SS',你可以使用

[...(function* g(x,n=0,scales=[60,60]){if(x>0||n<3) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().map(x=>String(x).padStart(2, '0')).join("-")

此外,如果你需要的是'[H:]MM:SS',这里我们有:

Number.prototype.toTimeString = function(){ 返回[…(*函数g (x, n = 0,鳞片= (60 60)){if (x > 0 | | n < 2){收益率x %(尺度[n] | |∞);产量* g (Math.floor (x /鳞片[n]), n + 1,尺度)}})(这)]. map ((x, n) = > n < 2 ?字符串(x) .padStart (2, ' 0 '): x) .reverse () . join(“:”) } console.log (12 (12) .toTimeString ()) console.log (345, (345) .toTimeString ()) console.log (6789, (6789) .toTimeString ())

你也可以有D(ay),甚至M(onth)和Y(ear)(虽然不准确),如下所示:

> toScaledArray(123456789,[60,60,24,30,12]).map((x,n)=>n<2?String(x).padStart(2,'0'):x).reverse().join(":")
< '3:11:18:21:33:09'

这里输出的意思是“3年11个月18天21小时33分9秒”

总之,这是一种高度可定制的将数字转换为可缩放数组的方法,可用于时间字符串转换、人类可读的字节转换甚至纸币的更改。