Date/Time formatting

#1

hi@all

I need a string like this:
“2018-06-28 08:44:55.000000”

So I tried to format the date:
var d = new Date();
var options = { timeZone: 'UTC', year: 'numeric', month: '2-digit', day: '2-digit'};
var _resultDate = d.toLocaleDateString('de-CH', options);
msg.payload = _resultDate;
return msg;

but Output says: “Thu Jun 28 2018”
thats not a swiss-german format nor I wanted to see the weekday

besides, 1st parameter of “toLocaleDateString” is completely ignored by node-red
“var _resultDate = d.toLocaleDateString(‘maradonna’, options)” gives me the same output w/o an error in the debug window

I’m confused

thx a lot for any advises
a node-red beginner

Changing global variable inside the function node
#2

Node.js is not built with all of the necessary locale information needed to fully support toLocaleDateString - see https://github.com/nodejs/node/issues/8500

Have a look at https://flows.nodered.org/node/node-red-contrib-moment as an alternative node for working with formatted date/times.

#3

thx knolleary

the output of the moment-node is perfect wiht this format: YYYY-MM-DD hh:mm:ss.ms
but is it possible to use the moment node/function inside another node, e.g. function-node?

#5

Hello na-am

Maybe is usefull for you, I'm actually using on my flows several format ways, once you have installed the "moment" node you can inject a timestamp once a second and configure the moment node to write the value on the format you wanted to a global variable, so you can acces this value with this format anywhere you need on your flows.

image

#6

Technically you could, but that’s a lot of wasted processing if you don’t need it every single second…

#7

In fact I’m actually doing like this with many more things and had not took the time to change it because the actual CPU load is really low, anyway can be inserted before the function he is writting and will have same effect but without any non-required load.

Regards

#8

It isn’t, it is designed to be part of a wider flow for folk who aren’t so good with JS. You could make use of the underlying MomentJS library if you need something special.

#9

Hey folks.

First off

var date;
date = new Date(timestamp);
date = (date.getFullYear() + '-' + ('00' + (date.getMonth()+1)).slice(-2) + '-' + ('00' + date.getDate()).slice(-2) + ' ' + ('00' + date.getHours()).slice(-2) + ':' + ('00' + date.getMinutes()).slice(-2) + ':' + ('00' + date.getSeconds()).slice(-2));

should do the trick (timezone proof)

But I have a question/problem regarding time formatting on an other front i have problems to wrap my mind around.

I've set up a fairly neat UI with the intention (besides the usual -continuous- monitoring stuff) to compare (overlaying) different dates of sensor data (e.g. temperature data of 21st August and 16th June). All fine and dandy... the selection, queries, processing and so on.. until it arives at the chart.

Using the timestamp of sql i'm obviously running into a problem - the date component of datetime/timestamp. But it seems that the chart can't handle time (HH:mm:ss) structured data (of curtime()).
(It looks like only the last key of the array is grabbed and set to min on the x-axis - even the value is missing)

The manually (function-)formatted (and joined) "JSONata"-structure - the input of the chart - looks fine. (use it successfully with timestamped sql data on my continuous stuff) Am I missing something?

Would be nice if someone who accomplished somewhat similar could point me in the right direction.

#10

Hola Davidcgu,

como haces para que despues de setear el "Output to = global.date3" lo puedas llamar desde cualquier otro flow? soy nuevo en el Node-RED y he estado tratando despues de leer tu post.

Saludos y gracias de antemano

#11

Buenas

Disculpa pero no habia visto tu post hasta ahora.

Puedes hacerlo directamente con el nodo "change" o con una funcion.

Como ejemplo mira de importar el flow que acabo de posterar en otro hilo de como hacer un boton que cambie el texto,el color y de 0 o 1 cada vez que pulses, igual te interesa y veras como hago uso de ambos metodos (que puedes utilizar independientemente para leer o escribir segun prefieras)

[{"id":"8d2594ef.698d08","type":"switch","z":"75be3680.18cac8","name":"ON/OFF state","property":"switch","propertyType":"global","rules":[{"t":"eq","v":"1","vt":"str"},{"t":"eq","v":"0","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":480,"y":360,"wires":[["ab336f93.c9655"],["508ad1d9.d0683"]]},{"id":"ab336f93.c9655","type":"function","z":"75be3680.18cac8","name":"if is on","func":"msg.color = \"black\";\nmsg.background = \"#EF2F4F\";\nmsg.text = \"TURN OFF\";\nreturn msg;","outputs":1,"noerr":0,"x":630,"y":320,"wires":[["56f03a62.8a0884"]]},{"id":"508ad1d9.d0683","type":"function","z":"75be3680.18cac8","name":"if its off","func":"msg.color = \"black\";\nmsg.background = \"#B4EEB4\";\nmsg.text = \"TURN ON\";\nreturn msg;","outputs":1,"noerr":0,"x":640,"y":380,"wires":[["56f03a62.8a0884"]]},{"id":"56f03a62.8a0884","type":"ui_button","z":"75be3680.18cac8","name":"on/off","group":"ac2c8e97.2a413","order":5,"width":"7","height":"1","passthru":false,"label":"{{msg.text}}","color":"{{msg.color}}","bgcolor":"{{msg.background}}","icon":"ac_unit","payload":"none","payloadType":"str","topic":"button","x":790,"y":340,"wires":[["69fa3686.0a8ef8"]]},{"id":"69fa3686.0a8ef8","type":"switch","z":"75be3680.18cac8","name":"","property":"topic","propertyType":"msg","rules":[{"t":"eq","v":"button","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":930,"y":340,"wires":[["19fd650d.56963b"]]},{"id":"97ec2c21.d6aec","type":"inject","z":"75be3680.18cac8","name":"","topic":"","payload":"0","payloadType":"str","repeat":"","crontab":"","once":true,"onceDelay":"3","x":110,"y":260,"wires":[["7cbb7fc1.8618e"]]},{"id":"7cbb7fc1.8618e","type":"change","z":"75be3680.18cac8","name":"global switch start","rules":[{"t":"set","p":"switch","pt":"global","to":"0","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":370,"y":260,"wires":[[]]},{"id":"96577bb1.6a6968","type":"inject","z":"75be3680.18cac8","name":"","topic":"","payload":"","payloadType":"date","repeat":"0.1","crontab":"","once":true,"onceDelay":0.1,"x":90,"y":360,"wires":[["65a47c10.e24204"]]},{"id":"19fd650d.56963b","type":"function","z":"75be3680.18cac8","name":"set output","func":"var obtaindata = global.get (\"switch\")\nif (obtaindata == \"1\"){msg.payload = 0}\nif (obtaindata == \"0\"){msg.payload = 1}\nreturn msg;\n\n","outputs":1,"noerr":0,"x":1060,"y":340,"wires":[["aaa11540.2dc088","acb5e0be.d3ead"]]},{"id":"aaa11540.2dc088","type":"debug","z":"75be3680.18cac8","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":1290,"y":340,"wires":[]},{"id":"acb5e0be.d3ead","type":"change","z":"75be3680.18cac8","name":"re-wirte switch variable","rules":[{"t":"move","p":"payload","pt":"msg","to":"switch","tot":"global"}],"action":"","property":"","from":"","to":"","reg":false,"x":1180,"y":280,"wires":[[]]},{"id":"b1729eea.50b7","type":"inject","z":"75be3680.18cac8","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":720,"y":420,"wires":[["53f47fc.c84908"]]},{"id":"53f47fc.c84908","type":"function","z":"75be3680.18cac8","name":"check variable value for debug","func":"var obtaindata = global.get (\"switch\");\nmsg.payload = obtaindata;\n\nreturn msg;\n","outputs":1,"noerr":0,"x":970,"y":420,"wires":[["aaa11540.2dc088"]]},{"id":"65a47c10.e24204","type":"function","z":"75be3680.18cac8","name":"read globl variable","func":"var obtaindata = global.get (\"switch\");\nmsg.payload = obtaindata;\n\nreturn msg;\n","outputs":1,"noerr":0,"x":290,"y":360,"wires":[["8d2594ef.698d08"]]},{"id":"ac2c8e97.2a413","type":"ui_group","z":"","name":"test","tab":"d92ab4b4.55f5c8","order":3,"disp":true,"width":"7","collapse":true},{"id":"d92ab4b4.55f5c8","type":"ui_tab","z":"","name":"test","icon":"fa-television","order":2}]

Para hacerlo en una funcion usarias el metodo get/set en función de si quieres leer el estado o escribir: var obtaindata = global.get ("switch"); global.set("switch") = 0;

En el caso de la fecha yo lo uso para añadir la hora exacta en el msg.payload para indicar por ejemplo cuando se ha abierto la puerta usando la siguiente función:

[{"id":"603c39c6.fc09d8","type":"function","z":"645f37da.84cc38","name":"puerta abierta","func":"var temp = global.get(\"date3\");\nmsg.payload = \"Puerta abierta >> \" + temp + '<br>';\nreturn msg;","outputs":1,"noerr":0,"x":460,"y":240,"wires":[["da2c6a92.068058"]]}]
var temp = global.get("date3");
msg.payload = "Puerta abierta >> " + temp + '<br>';
return msg;

Esta función cada vez que es llamada me devolvera el mensaje puerta abiert y la hora a la que ha sucedido en el formato del date3 que es el que uso para este mensaje.
Nota: el '
' lo añado solo porque en este caso concreto envio el mensaje a un archivo y este br lo que hace es que posteriormente cuando leo el contenido del archivo para visualizarlo en la pantalla en node red y ver el historial de mensajes crea una linea a parte.

Espero te sirva de ayuda

Un saludo