Is there a way to get the timestamp in the JSON msg? I know there is msg.payload and msg.topic, but wanted to add a timestamp to a new variable in the format of "YYYY-MM-DD HH:MM:SS" Any known methods or ideas on how I can do this within Node-RED?
Answer by Gari Singh (604) | Aug 12, 2014 at 12:42 PM
I am not quite sure exactly what you are asking here, so apologies if I am answering the wrong question.
I don't think that the msg object has a timestamp property coming out of any of the nodes. I think it is just added when debug prints to the console.
So you basically need to generate a timestamp and set a variable each time a message arrives in your Node-RED flow.
The easiest thing would be to add a "function" node and just insert some simple JavaScript to generate the date and then add it to a property on the "msg" object so that the next node in the flow has access to it.
If you would be ok using an ISO date format (YYYY-MM-DDTHH:mm:ss.sssZ), then you can simply do something like
msg.timestamp= new Date().toISOString()
If you want to use the "YYYY-MM-DD HH:MM:SS" format, then you would do something like:
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
msg.timestamp = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;