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
const hms = '02:04:33'; const [hours, minutes, seconds] = hms. split(':'); const totalSeconds = (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds); console. log(totalSeconds);
format(); moment(). format(String); This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With