Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

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

How can I convert seconds to 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}).*/, "$1");;
}

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

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 without moment.js which is as follow

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...