Moment is not defined & format to get duration of seconds

I am trying to subtract time now() with data from mysql.
Over here, M_Start = "08:15:00"
Example Current = "22:02:39"
My intention is to get total seconds of the different .
While using moment function : error message : "ReferenceError: moment is not defined (line 22, col 9)"

var ST_Target;
var Shift_Target;

var M_Start = flow.get('Morning_start');
var M_Stop =flow.get('Morning_end');
var M_sec = flow.get('Morning_sec');

var M_cycle = flow.get("Cycle_Time");

var dt = new Date();
var hour = dt.getHours();
hour = ("0" + hour).slice(-2);

var minute = dt.getMinutes();
minute=("0" +minute).slice(-2);

var sec = dt.getSeconds();
sec=("0" + sec).slice(-2);

var current = hour+":" +minute+":"+sec;

var d = moment.duration(current.diff(M_Start[0]));


I did install the module from the link below.

var momentjs = require("node-red-contrib-moment");

var ST_Target;
var Shift_Target;

var M_Start = flow.get('Morning_start');
var M_Stop =flow.get('Morning_end');
var M_sec = flow.get('Morning_sec');
.....

The error still persist -> "ReferenceError: require is not defined (line 1, col 16)"

What versions of NR, Node and what OS are you running on ??

Craig

Hi @tramanah

Installing node-red-contrib-moment will add the Moment nodes to your palette. It does not cause the moment library to be available in the Function node.

The Function node cannot require modules directly. If you really want to install another npm module and make it available in the Function node, the docs explain how to do that: https://nodered.org/docs/writing-functions#loading-additional-modules

1 Like

Feed the two times into new Date() to create two JavaScript date/time objects. You can then subtract them and get the difference in milliseconds.

thank you, its works

var current = hour+":" +minute+":"+sec;
var curr = current.split(":");
var Mor = M_Start[0].split(":");

var startCurr = new Date(0,0,0, curr[0],curr[1],curr[2]);
var startMor = new Date(0,0,0, Mor[0],Mor[1],Mor[2]);

var diffM = startCurr.getTime() - startMor.getTime();
var Min = Math.floor(diffM/1000/60);