0

I get a time difference from mongodb:

9.266666666666667

and rounded it off to two decimal places:

9.27

Now i want to format it to 00:00 time format. And i tried to format this using moment js:

moment(9.27).format('HH:mm')

But it returns:

08:00 

which is wrong.

It should be:

09:16

Anyone have ideas? Thank you.

noyruto88
  • 767
  • 2
  • 18
  • 40
  • `a time difference` ... seconds? minutes? hours? days? what *unit* is the time difference? – Jaromanda X Mar 05 '18 at 05:51
  • 1
    9.27 milliseconds after the Date epoch is 1970-01-01T00:00:00.009Z - converted to your timezone, it coould be any time I guess, depending on your timezone – Jaromanda X Mar 05 '18 at 05:56
  • Duplicate of [*How to convert decimal hour value to hh:mm:ss*](https://stackoverflow.com/questions/35460303/how-to-convert-decimal-hour-value-to-hhmmss?s=1|122.6979)? – RobG Mar 05 '18 at 05:57
  • @JaromandaX—well, any time within +14 or -11 hours of that time. ;-) – RobG Mar 05 '18 at 06:02
  • I got my time difference with this code: db.collectionname.aggregate([ {$project: { duration: {$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]} }} ]) from https://stackoverflow.com/questions/41138877/how-to-calculate-timestamp-difference-in-mongodb-in-hours – noyruto88 Mar 05 '18 at 06:03

2 Answers2

2

I found the answer based from this post: How to convert decimal hour value to hh:mm:ss

var time_formatted = moment().startOf('day').add(parseFloat(9.266666666666667), "hours").format("hh:mm");
noyruto88
  • 767
  • 2
  • 18
  • 40
0

If 9.27 really needs to be translated into 09:27, you can parse it as a glued hour/minute: console.log(moment(9.27, "hhmm").format("HH:mm")) // 09:27

However, as others have pointed out, note that 9.27 hours is NOT 9h 27min.

tverghis
  • 957
  • 8
  • 31
  • If that is all that's required, then simple string replace, e.g. `(''+9.27).replace('.',':')`, would be far better than using a date library. – RobG Mar 05 '18 at 05:59
  • I edited my questions. I think it should be 09:16 since it is a time difference. Thank you. – noyruto88 Mar 05 '18 at 06:29