Compare Actual Time with Node-Red Time

Hi all,

is it possible to compare the actual time to a given time and act accordingly ?
The code that I already have looks like this, but I do not how know to get the actual time from node-red and compare it to a planned time:

IF (pump_status == "ZP1"){
    IF (06:00)  set switch_Status = "ON";
    IF (06:02)  set switch_Status = "OFF";
    IF (07:00)  set switch_Status = "ON";
    IF (07:00)  set switch_Status = "OFF";
}

IF(pump_status == "ZP2"){
    IF(09: 00)  set switch_Status = "ON";
    IF(09: 05)  set switch_Status = "OFF";
    IF(11: 15)  set switch_Status = "ON";
    IF(11: 22)  set switch_Status = "OFF";
}

if (switch_status == "ON" && pump_status == "OFF")   return [msg,null];  // Turn On
if (switch_status == "OFF" && pump_status == "ON")   return [null,msg];  // Turn Off

You can get the current local time in Node-RED as a string with a function node containing the following:

msg.payload = time();
function time() { return { time: new Date().toLocaleTimeString() } };
return msg;

You can read more about the JavaScript Date object here: Date - JavaScript | MDN

Yes, of course.

However, you will find it a LOT easier if you use one of the existing contributed nodes that will do this comparison for you. For example, the CRON+ node lets you set outputs based on time of day as do several other nodes. For example, I often use node-red-contrib-sun-position instead of node-red-contrib-cron-plus. Depends on what you find easiest and most convenient.#

But here is a more complex example from one of my lights - it is using CRON+ directly. But the sun-position nodes are used elsewhere to set wake/sleep and daylight/nighttime flags via MQTT.

unfortunately this gives a wrong timezone

image

it is 22:52 right now, but the query says it is 20:52

It says it is 2052 UTC (that is what the Z means) so I expect that is the right time, just displayed differently. 20:52 UTC is the same time as 22:52 UTC+2. In what format is the time that you want to compare it with? Where is that timestamp coming from?

Yes that could be the case.
UTC is 2hrs behind my local time.

I want to compare with local time - right now it would be "23:16"
The timestamp comes from new Date().toLocaleTimeString()
The Value on top is the debugger timestamp

In that case use this:

// get a timestamp
const event = new Date();
// convert to local time
msg.payload = event.toLocaleTimeString("en-US", { timeZone: "Europe/Berlin" });
return msg;

I meant where is the time that you want to compare with the current time coming from and what format is it in?

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