Javascript 如何在 moment.js 中将秒转换为 HH:mm:ss

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31337370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:32:48  来源:igfitidea点击:

How to convert seconds to HH:mm:ss in moment.js

javascriptmomentjs

提问by QGA

How can I convert seconds to HH:mm:ss?

如何将秒转换为HH:mm:ss

At the moment I am using the function below

目前我正在使用下面的功能

render: function (data){
     return new Date(data*1000).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "");;
}

This works on chrome but in firefox for 12 seconds I get 01:00:12I would like to use moment.js for cross browser compatibility

这适用于 chrome,但在 Firefox 中运行 12 秒,我01:00:12想使用 moment.js 来实现跨浏览器兼容性

I tried this but does not work

我试过这个但不起作用

render: function (data){
         return moment(data).format('HH:mm:ss');
}

What am I doing wrong?

我究竟做错了什么?

EDIT

编辑

I managed to find a solution withoutmoment.js which is as follow

我设法找到了一个没有moment.js的解决方案,如下所示

return (new Date(data * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];

Still curious on how I can do it in moment.js

仍然对我如何在 moment.js 中做到这一点感到好奇

采纳答案by mplungjan

From this postI would try this to avoid leap issues

这篇文章中,我会尝试这样做以避免飞跃问题

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

我没有运行 jsPerf,但我认为这比创建新的日期对象一百万次要快

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

for (var i=60;i<=60*60*5;i++) {
 document.write(hhmmss(i)+'<br/>');
}


/* 
function show(s) {
  var d = new Date();
  var d1 = new Date(d.getTime()+s*1000);
  var  hms = hhmmss(s);
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}    
*/

回答by Sophie

This is similar to the answer mplungjan referenced from another post, but more concise:

这类似于从另一篇文章中引用的答案 mplungjan,但更简洁:

const secs = 456;

const formatted = moment.utc(secs*1000).format('HH:mm:ss');

document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

它也有同样的警告,例如,如果秒数超过一天 (86400),您将无法获得预期的结果。

回答by Oleksiy Kachynskyy

You can use moment-duration-formatplugin:

您可以使用moment-duration-format插件:

var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

See also this Fiddle

另见这个小提琴

回答by yehonatan yehezkel

var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format =  Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();

回答by Farrukh Malik

How to correctly use moment.js durations?| Use moment.duration() in codes

如何正确使用 moment.js 持续时间?| 在代码中使用 moment.duration()

First, you need to import momentand moment-duration-format.

首先,您需要导入momentmoment-duration-format.

import moment from 'moment';
import 'moment-duration-format';

Then, use duration function. Let us apply the above example: 28800 = 8 am.

然后,使用持续时间函数。让我们应用上面的例子:28800 = 8 am。

moment.duration(28800, "seconds").format("h:mm a");

Well, you do not have above type error. Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.

好吧,您没有上述类型错误。你在上午 8:00 得到正确的值吗?不……,您得到的值是 8:00 a。Moment.js 格式无法正常工作。

The solution is to transform seconds to milliseconds and use UTC time.

解决方案是将秒转换为毫秒并使用 UTC 时间。

moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')

All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp

好的,我们现在是上午 8:00。如果你想要 8 am 而不是 8:00 am 积分时间,我们需要做 RegExp

const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')

回答by dev adgh1

Until 24 hrs. As Duration.formatis deprecated, with [email protected]

直到 24 小时。由于Duration.format已被弃用,与[email protected]

const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');