简体   繁体   中英

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

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, eg if seconds exceed one day (86400), you'll not get what you expect.

From this post I 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

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]); } */

You can use moment-duration-format plugin:

 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

Upd: To avoid trimming for values less than 60-sec use { trim: false } :

var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"
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();

My solution for changing seconds (number) to string format (for example: 'mm:ss'):

const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');

Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.

Until 24 hrs. As Duration.format is deprecated, with moment@2.23.0

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

In a better way to utiliza moments.js; you can convert the number of seconds to human-readable words like ( a few seconds, 2 minutes, an hour).

Example below should convert 30 seconds to "a few seconds"

moment.duration({"seconds": 30}).humanize()

Other useful features: "minutes", "hours"

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

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

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

Then, use duration function. Let us apply the above example: 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.

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

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

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

The above examples may work for someone but none did for me, so I figure out a much simpler approach

  var formatted = moment.utc(seconds*1000).format("mm:ss");
  console.log(formatted);

To display number of days along with hours, mins and seconds, you can do something like this:

const totalSec = 126102;
const remainingMillies= (totalSec % 86400) * 1000;
const formatted = `${Math.floor(totalSec / 86400)} day(s) and ${moment.utc(remainingMillies).format('hh:mm:ss')}`;
console.log(formatted );

will output : 1 day(s) and 11:01:42

In 2022 no need for any new plugin just do this

Literally all you need in 2022 prints out duration in hh:mm:ss from two different date strings

<Moment format='hh:mm:ss' duration={startTime} date={endTime} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM