Add a Timestamp to Function node


I'm using the following flow to read a Modbus power meter Flow 2, this is the string in the function node Function node. I would like to add a time format to the msg.payload.

something like this

{"Time": 2020-03-04 12:15:10}

1 Like

Do you mean {"Time": 2020-03-04 12:15:10, "Voltage":228.16} in the payload?
Can I first ask why you want the time as a string rather than a javascript timestamp? Often it is best to keep it as a timestamp and only convert to string when needed for display.

Yes that would work too, I'm still learning in node-red. I need the timestamp so i can visualize it in AWS-cloud analytics.

That is very easy then, if you pass the message containing a payload of {"Voltage":228.16} to a function node containing

msg.payload.Time = new Date()
return msg;

then that will do it. That assumes you already have the voltage property already setup. If you just have that value as a number in the payload then you can put them both in using

msg.payload = {Time: new Date(), Voltage: msg.payload}
return msg;

Thanks for the help Colin! it worked for me!

Personally, I would output the timestamp in an ISO format because that is easily processed and cannot be misinterpreted but is still human readable.

msg.payload.Time = (new Date()).toISOString()
return msg;

Output looks like: 2020-03-04T15:13:21.294Z

Note that ISO timestamps are always in Zulu timezone (UTC).


Either way,.... this will often not work and give errors:

{"Time": 2020-03-04 12:15:10},

The time string needs to be a string, to be sure:

{"Time": "2020-03-04 12:15:10"}

so this will also will have problems, for the same reason:

{"Time": 2020-03-04 12:15:10, "Voltage":228.16}

Should be formatted in JSON as a string, to insure smooth sailing:

{"Time": "2020-03-04 12:15:10", "Voltage":228.16}

Sometimes when having problems (or just building JSON strings), it is a good idea to simply and quickly take your proposed JSON string and copy-and-paste it into some kind of visual editor which will format the JSON.

For example, I use Visual Studio Code, and when I have a JSON string when developing / programming, I quickly copy-and-paste the string into a VSC file with a .json extension and it either formats as a proper JSON string or it does not.

This will often save (us) a lot of time trying to get an API or JSON payload to work when there is some JSON formatting error.

How do you know? Does it not depend on where you are sending it? Sending a javascript date may be perfectly valid.
In addition if sending as a string it is often important to include the timezone information.
{Time: new Date()}
does that implicitly.

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