Issues calculating time between two timestamps

Hello Guys,

Hope everyone is well, I wonder if some one could assist me here, apologies in advance I'm very new to coding function nodes.

Im in the process of trying to turn my dumb paper shredder into a somewhat smart device so I can trigger proactive alerts when the device needs to be serviced.

In order to achieve this I need to work out the the time in seconds between when the machine is running and when it shuts off. Ive kind of got what I need but the formatting isn't correct.

My current flow will trigger when the device power consumption is over a set value, the flow injects a timestamp when it starts, it then waits for the power consumption to drop and then my function node works out of the time between the start and finish timestamps.

The code below seems to work however I producing an example output of -13.972

so my questions are:

1.) Im unsure why it is returning a negative value and how would I change it so the output is 13.972
2.) How would I then adapt my code so it rounds to the nearest second? in this example 14

var starttime = msg.starttime;
var diffMS = starttime - Date.now();
var diffS = diffMS / 1000;
msg.usage = diffS;
return msg;

Thanks in advance.

You are taking the current time away from the start time. Current time is larger than the start time. Try
Date.now() - starttime

Thank you, that worked perfectly what a noob error.

Any ideas how I can round the value to the nearest second?

Look at the javascript round() function.

Thank you Colin have this working now,

If anyone is interested:

var starttime = msg.starttime;
var diffMS = Date.now() - starttime;
var diffS = diffMS / 1000;
var round = Math.round(diffS)
msg.usage = round;
return msg;

You should generally not use var nowadays, it is better to use const or let. It won't make any difference in this case but it is better to use the newer directives.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.