Help to make a quick bit of code with Date/Time and message

(Don't know why but some of the suggestions offered at the start won't open)

I asked chatGPT and it doesn't seem to work.

// Get the current date and time
let now = new Date();

// Format the date to a human-readable string
let options = { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit', 
    timeZoneName: 'short' 
};

// Convert to human-readable format
msg.payload = now.toLocaleString('en-AU', options); // Change 'en-US' to your preferred locale

return msg;

The options part throws an error at me.

I want a node that accepts a payload (used) and makes a human readable date/time mark and appends the payload.

Sorry, brain not working.

This code seems to work.

// Get the current date and time
let now = new Date();

let message = msg.payload

// Extract the components
let year = now.getFullYear();
let month = String(now.getMonth() + 1).padStart(2, '0'); // Months are 0-based
let date = String(now.getDate()).padStart(2, '0');
let hours = String(now.getHours()).padStart(2, '0');
let minutes = String(now.getMinutes()).padStart(2, '0');

// Format the payload
msg.payload = `${year}/${month}/${date} ${hours}:${minutes}` + " " + message;

return msg;

Given msg.payload has a message I want included in the outgoing message.

Stupid TS checker.

Add this on the line before the error:

// @ts-ignore

:slight_smile:

Thanks but you lost me.

It is a case of the TypeScript engine not understanding how to use that JavaScript function properly. So you can ignore the error. Using @ts-ignore in the comment before the line will tell the Monaco editor to ignore the error.

1 Like

WOW!

That is left of field for me. (dunno if that is the right saying.)

(Good news / Bad news though)

I have since found Date/Time Formatter node.

That allows me to adjust the structure of the output.
That seems to do a a nicer job and is easier to use.

But I shall have to really try to remember that trick.

Try

msg.payload = new Intl.DateTimeFormat('en-AU', options).format(now)

instead of

msg.payload = now.toLocaleString('en-AU', options)
1 Like

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