1

AM trying to format momentjs to hh:mm:ss in over 24 hours but i only get 1 hour so i have tried

 const start = moment('2019-02-27 00:00');
 const end = moment('2019-03-01 01:00');
 var diff =end.diff(start, 'seconds', true)

 let ff = moment.utc((diff) * 1000).format('HH:mm:ss')

 console.log(ff)

In the above i expected to get

49:00:00

as its two days and 1 hour so 24*2 since each day has 24 hours plus the one hour from 00:0 to 01:00

WHere am i going wrong as it shows 01:00:00 instead of 49:00:00

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • I believe you can't achieve this with moment.js as it will always print a max of '24' in the hours value – Ghonima Mar 08 '19 at 12:30
  • 1
    February 27th to April 2nd is a lot more than 49 hours. – Pointy Mar 08 '19 at 12:32
  • @Pointy i see i have updated with correct ranges – Geoff Mar 08 '19 at 12:40
  • Your difference might effectively be 49 hours - but from the point of view of such a date library, it is actually 2 days and 1 hour. And therefor, you get `01:00:00` as a result, when you try and format this as `HH:mm:ss`. The existing format options do not seem to cover what you want (it is a _date_ library, not a work-with-arbitrary-intervals-library), so I think you will have to write something that gets you the correct amount of hours yourself. – 04FS Mar 08 '19 at 12:46
  • By the way, your end date is wrong. You have the year as 2016 when it should be 2019. With the correct dates, the variable diff outputs 49. From there you can then write something (to echo 04FS's comment) to format it how you wish. – Doug F Mar 08 '19 at 13:28
  • @DougF thanks i have updated – Geoff Mar 08 '19 at 14:11
  • @04FS thanks. I thought momentjs had this. – Geoff Mar 08 '19 at 14:13

1 Answers1

1

Also run into the same problem, heres my code snippet if that would help you.

let start = moment('2019-03-01 00:00:00');
let stop = moment();

const formatTimespan = (start, stop) => {
  const diff = stop.diff(start, "hours", true);

  const hours = Math.floor(diff);
  const step = 60 * (diff - hours)
  let mins = Math.floor(step)
  let secs = Math.floor(60 * (step - mins));
  mins = mins.toString().padStart(2, "0");
  secs = secs.toString().padStart(2, "0");
  return `${hours}:${mins}:${secs}`;  
}

console.log(formatTimespan(start, stop));
BraveButter
  • 1,408
  • 9
  • 22