QGA
QGA

Reputation: 3192

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

Upvotes: 127

Views: 190726

Answers (12)

Hicham O'Sfh
Hicham O'Sfh

Reputation: 841

I think there's no need to use 3rd part libray/pluggin to get this task done
when using momentJS version 2.29.4 :

  private getFormatedDuration(start: Date, end: Date): string {
    // parse 'normal' Date values to momentJS values
    const startDate = moment(start);
    const endDate = moment(end);

    // calculate and convert to momentJS duration 
    const duration = moment.duration(endDate.diff(startDate));

    // retrieve wanted values from duration
    const hours = duration.asHours().toString().split('.')[0];
    const minutes = duration.minutes();

    // voilà ! without using any 3rd library ..
    return `${hours} h ${minutes} min`;
  }

supports also 24h format
PS : you can test and calculate by yourself using a 'decimal to time' calculator at CalculatorSoup

Upvotes: 0

KingJoeffrey
KingJoeffrey

Reputation: 391

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} />

Upvotes: 0

M.A.Naseer
M.A.Naseer

Reputation: 343

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

Upvotes: 0

Peter
Peter

Reputation: 1275

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);

Upvotes: 6

Sharhabeel Hamdan
Sharhabeel Hamdan

Reputation: 1549

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"

Upvotes: 5

Adi Dasler
Adi Dasler

Reputation: 528

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.

Upvotes: 8

Oleksiy Kachynskyy
Oleksiy Kachynskyy

Reputation: 683

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"

Upvotes: 31

dev adgh1
dev adgh1

Reputation: 129

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

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

Upvotes: 4

Farrukh Malik
Farrukh Malik

Reputation: 796

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, '')

Upvotes: 1

mplungjan
mplungjan

Reputation: 177786

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

Upvotes: 97

yehonatan yehezkel
yehonatan yehezkel

Reputation: 1248

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();

Upvotes: 19

Sophie
Sophie

Reputation: 2070

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.

Upvotes: 158

Related Questions