Ok, I kinda got the other question working/resolved.
But in doing so I found ANOTHER gremlin lurking under the covers.
new Date().toLocaleString();
For reasons unknown to me, it gives me time with those pesky AM/PM things.
I want 24 hour time. LOCAL.
Seems that bit of code has snuck into a few nodes I am using.
How do I get it to give me the time in 24 hour format?
Please.
Given this code gives me 24 hour time:
// 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;
And this code just has an error with the options part - as mentioned in the other thread.
const now = new Date();
// Set options for 24-hour format
const options = {
hour: '2-digit',
minute: '2-digit',
hour12: false // Set to false for 24-hour format
};
// Get the time in 24-hour format
const time_ = now.toLocaleString('en-AU', options);
console.log(time_);
const now = new Date();
// Set options for 24-hour format
const options = {hour: '2-digit', minute: '2-digit', hour12: false};
// Get the time in 24-hour format
const time_ = now.toLocaleString('en-AU', options);
msg.payload = time_
return msg;
Honestly Paul, this is a problem/thing that recently popped up needing my attention and I was stuck with how to format the time/date (date/time) to a specific format.
I'm going around reformatting the date/time on logs.
So rather than getting (example) 2024/10/15 18:06:33
I just need 15/10 18:06:33
Then I have the DATE, MONTH and time.
Then the log file (although already in that order) you see the date, then month, then time. Then the event that happened.
The older code did do it, but as I only now realised has AM/PM time.
(Cringe)
So I was trying to get it in 24 hour time.
Asked ChatGPT and got a bit of code, but the code says the options is invalid.
Yeah, it (chat GPT) isn't perfect.
But I don't understand why it offered it to me and what is wrong with it and where the options comes into how it works.
All my other excursions into JS on other sites didn't really mention the options or didn't explain it well enough.
It just Seems to be taken as it is globally understood how it works..
const now = new Date()
// Set options for 24-hour format and day/date
const options = {
day:'2-digit',
month: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false // Set to false for 24-hour format
}
// Get the time in 24-hour format with date as day/month (example: 15/10, 20:16 )
const dateTime = new Intl.DateTimeFormat('en-AU', options).format(now)
msg.time = dateTime
return msg