Convert yyyymmdd format within a string to epoc

Hi all
wondering if anyone could provide a method (function or change node) of taking a string like this from a payload "SG3.0RS,ON,2024-7-12 14:36:10,0.0,0.0,11.8,38.5,46,41.4,1291,241.6,1287,Run,415,38.5,Start,2024-7-12 14:36:10,0,0" and replacing the yyyymmdd values in it with the epoch value.
Thank you in advance.
Dan

Assuming the structure is consistent, the easiest way, if you know a bit of JavaScript, would be a function node. Split the string by comma's, extract the date/time entry then feed that into a JS Date, something like this (untested):

const splitMsg = msg.payload.split(',')
const dt = splitMsg[2]

let mydate = new Date(dt)

// to get the UNIX Epoch rather than a JS timestamp
mydate = mydate / 1000 

msg.payload = mydate

return msg

BTW, the Monaco editor will complain about the division as it believes that a JavaScript Date object is not a number. One of the many oddities of JS is that Dates ARE BOTH. :grinning: Ignore or cast mydate to a number if you prefer.

1 Like

If you want to replace bothe YYYY-MM-DD HH:mm:ss values, here is a change node option.

[{"id":"34555c4b1ece4315","type":"inject","z":"d1395164b4eec73e","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"SG3.0RS,ON,2024-7-12 14:36:10,0.0,0.0,11.8,38.5,46,41.4,1291,241.6,1287,Run,415,38.5,Start,2024-7-12 14:36:10,0,0","payloadType":"str","x":110,"y":180,"wires":[["db89616e8c66ea88"]]},{"id":"db89616e8c66ea88","type":"change","z":"d1395164b4eec73e","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"(\t    $part := $split($$.payload, \",\")[2];\t    $replace($$.payload, $part, $moment($part).format(\"x\"))\t)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":260,"y":180,"wires":[["c9747f50f33b19c5"]]},{"id":"c9747f50f33b19c5","type":"debug","z":"d1395164b4eec73e","name":"debug 2562","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":470,"y":180,"wires":[]}]

This only works if Both date values are the same.

1 Like

you guys are amazing thank you both for the quick responses

1 Like

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