Add time offset to a date object in Node-RED function

204 views Asked by At

I need to add a number of milliseconds to a date object in a function in Node-RED and I've addressed it using the .toMilliseconds() method (not sure if there is a more efficient way to do it)

I instance two objects of Date type and add the number of milliseconds to one of them:

finish.setMilliseconds(finish.getMilliseconds() + 200);

The reason to instance two object and initialize them with exactly the same value is to be able to later calculate the lapse between them (the offset will not be constant, otherwise I'd know the lapse)

So far, so good.

The issue comes when I try to use the other date object, as it takes the value of the modified one, with the milliseconds added:

let start = new Date();
let finish = start;

msg.TS = start.toISOString();

finish.setMilliseconds(finish.getMilliseconds() + 200);

msg.TS2 = finish.toISOString();

msg.TS3 = start.toISOString();

return msg;

This is the output in the debug window:

  TS: "2023-09-27T14:51:36.522Z"
  TS2: "2023-09-27T14:51:36.722Z"
  TS3: "2023-09-27T14:51:36.722Z"

TS3 should contain the original datetime rather than the modified one, shouldn't it?

Do start and finish take the same values because of how they are declared?

Thanks!

** EDIT **

I've found the reason and a solution. Instancing the objects in this way, it works as expected (although I still don't know why failed. may be memory addresses sharing?):

let start = new Date();
let finish = new Date(start);
0

There are 0 answers