3

I have 2 timestamps and i already calculated the time difference in minutes with moment plugin. Now i want to convert the minutes to HH:mm.

var x = moment('10:00', 'HH:mm');
var y = moment('11:30', 'HH:mm');
var diff = y.diff(x, 'minutes'); // 90 
var convert = moment.duration(diff, "minutes").format('HH:mm');
alert(convert); // should give me 01:30 but does not work

What i am doing wrong?

john
  • 1,263
  • 5
  • 18
  • What is the error coming? – Sunny May 18 '21 at 19:47
  • `Uncaught TypeError: moment is not a function` – john May 18 '21 at 19:47
  • this looks like a duplicate: https://stackoverflow.com/questions/13262621/how-to-use-format-on-a-moment-js-duration . I get a different error, curiously (it complains that format is not a function on a duration object) so there may be something environment-specific too, but you're not supposed to be able to format durations (with moment alone), and you never will be. Cf. https://github.com/moment/moment/issues/1048 . – neofelis May 18 '21 at 19:56

1 Answers1

1

Since you have not specified what is the error, I'm assuming you are leaving the dependencies required for duration method.

The moment-duration-format depends on moment, so you should require it before using it.

npm install moment moment-duration-format

Then either you can import the dependencies or require them.

import moment from "moment";
import "moment-duration-format";

 var moment = require("moment");
  require("moment-duration-format");
  var x = moment("10:00", "HH:mm");
  var y = moment("11:30", "HH:mm");
  var diff = y.diff(x, "minutes"); // 90
  var convert = moment.duration(diff, "minutes").format("HH:mm");
  alert(convert);

Note: require is a Node.JS function and doesn't work in client side scripting without certain requirements. More info

Hope it helps Thanks

Sunny
  • 235
  • 4
  • 17
  • yes indeed. I got the error: `require is not defined` – john May 18 '21 at 19:54
  • I have updated my answer with a note, can you tell where are you using this code, in a NodeJS environment or in browser – Sunny May 18 '21 at 20:05
  • 1
    In a browser and i got it working now: In the head below moment plugin:``: and then the alert works fine WITHOUT these lines: `var moment = require("moment"); var momentDurationFormatSetup = require("moment-duration-format");` – john May 18 '21 at 20:14