How to calculate time difference?

#1

Hello;

I would like to calculate time when start 22:00:00 in the database and the end time is 02:30:00. Who has an idea for calculate 22:00:00 to 02:30:00( Total 04:30:00 Hour ) in the node-red? 

Thank you.

0 Likes

#2

Here is code I have used to figure sunset and sunrise .. perhaps this could help.
hr=msg.payload.sun_phase.sunrise.hour;
min=msg.payload.sun_phase.sunrise.minute;
srise = hr+':'+min;
sriseCalc = new Date();
sriseCalc = execTime(sriseCalc, srise, -15);
hr=msg.payload.sun_phase.sunset.hour;
min=msg.payload.sun_phase.sunset.minute;
sset = hr+':'+min;
ssetCalc = new Date();
ssetCalc = execTime(ssetCalc, sset, 15);
msg.payload = {sunrise : srise, sunset : sset,calcSunrise : sriseCalc.getTime(), calcSunset : ssetCalc.getTime()};
context.global.astroData = {calcSunrise : sriseCalc.getTime(), calcSunset : ssetCalc.getTime()};// context.global.astroData;
return msg;

function execTime (t, target, delay) {
arr = target.split(':');
t.setHours(arr[0]);
t.setMinutes(arr[1]);
t.setMinutes(t.getMinutes() + (delay));
return t;
}

0 Likes

#3

As always, don't forget to think about local vs UTC times. If using local, you need to take into account any daylight savings changes.

0 Likes

#4

Thank you very much. I will do it.

0 Likes

#5

Assuming the times are javascript Date objects then you can just subtract them to get the difference in milliseconds. Simple example:

[{"id":"6ad54371.3f495c","type":"inject","z":"514a90a5.c7bae8","name":"Go","topic":"","payload":"","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":86.5,"y":386,"wires":[["aefc190e.4d5228"]]},{"id":"aefc190e.4d5228","type":"function","z":"514a90a5.c7bae8","name":"Set start time","func":"var now = new Date();   // current time\nflow.set(\"startTime\", now);\nreturn msg;","outputs":1,"noerr":0,"x":242.5,"y":386,"wires":[["7a2a486a.8ed5e8"]]},{"id":"9ec23600.57f388","type":"function","z":"514a90a5.c7bae8","name":"Calc difference ms","func":"var now = new Date();\nmsg.payload = now - flow.get(\"startTime\");\nreturn msg;","outputs":1,"noerr":0,"x":579.5,"y":386,"wires":[["ddbc6e32.6a8f28"]]},{"id":"7a2a486a.8ed5e8","type":"delay","z":"514a90a5.c7bae8","name":"","pauseType":"delay","timeout":"3","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":408.5,"y":386,"wires":[["9ec23600.57f388"]]},{"id":"ddbc6e32.6a8f28","type":"debug","z":"514a90a5.c7bae8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":522.5,"y":495,"wires":[]}]
0 Likes