Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(/(\d\d:\d\d:\d\d)/)[0]; 

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

like image 899
QGA Avatar asked Jul 10 '15 09:07

QGA


People also ask

How do you convert HH MM SS to seconds in JavaScript?

const hms = '02:04:33'; const [hours, minutes, seconds] = hms. split(':'); const totalSeconds = (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds); console. log(totalSeconds);

What does format () do in moment?

format(); moment(). format(String); This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.

How do you convert moments to time?

Convert time If you are creating timestamps using built-in new Date() , you can also use it to create moment objects: const timestamp = new Date(); const momentTimestamp = moment(timestamp); If you want to create a moment object using current date and time, just call moment() without any arguments.

What will Moment () return?

Displaying Formatted Dates Moment. js helps display date with specified formats. moment() returns a date and format() converts the date string tokens and replaces them with specified format values, which are readable.


1 Answers

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>

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

like image 197
Sophie Avatar answered Sep 18 '22 09:09

Sophie