Problem with substr()

HELP!!!!
Substr wont split a string on Node red but works in codepen.io (javascript dev app)??

The following works on JavaScript nodepen.io but NOT on node red:
var tima = "2021-02-09T07:36:40:000Z.";
const ss = Number(String(datec).substr(11, 2);
console.log(ss);
This outputs 07 which is what you would expect

This is what is on node red but the var tima is replaced with msg.payload[0].datetime which exactly the same as 2021-02-09T07:36:40:000Z as above:.
var tima = msg.payload[0].datetime;
msg.payload = Number(String(tima).substr(11, 2));
return msg;
msg.payload outputs 07 which is what NOT what I expected.

Can any kind person tell me where I am going wrong. Thanks....

MISTAKE:
msg.payload outputs 20 which is NOT what I expected??

var tima = "2021-02-09T07:36:40:000Z.";

This is not a valid date format (should be 2021-02-09T07:36:40.000Z), if it were valid, you could use a change node with a jsonata+moment expression to extract the day.

Instead of using substr you could split it by T and then by - and get the last element;

let d = tima.split("T")[0].split("-")[2]
msg.payload = d
return msg

edit this extracts the wrong value I guess (topic was not clear on what you needed to extract), you can adapt the code to your liking, ie;

let d = tima.split("T")[1].split(":")[0]
1 Like

Or you could convert the string to Date object then you can use any of the Date functions to extract what you want.
let date = new Date(msg.payload[0].datetime)

But are you sure that the value in the payload is a string and not already a Date? Add the line

node.warn(`type is ${typeof msg.payload[0].datetime}`)

and see what it says.

1 Like

Hi, thanks for your help. I used Colin's suggestion and converted the string into a date object and it worked as I wanted.

Hi,

You said, that the expected result of your function would be 07. However that is not the case, it will be only 7.

I tested your following function:

var tima = "2021-02-09T07:36:40:000Z.";
msg.payload = Number(String(tima).substr(11, 2));
return msg;

If you omit Number the result of the function will be "07", which is a (sub) string.
The 12 th character in the string is 0 and then the string consist of 2 characters , so "07".
The Number() function converts it to a number, without the leading zero.

So the result is just a Number 7

1 Like

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