Format date at 'YYYY:MM:DD HH:MM;SS'

Hello.
How can you format the date in the logs? now I have it '23 Nov 2023 hh:mm:ss'
it must have been so 'YYYY:MM:DD HH:MM;SS'
Writing a function just adds the date again((

const currentDate = new Date();
const formattedDateTime = currentDate.toISOString().replace(/T/, ' ').replace(/\..+/, '');

const { loggingLevel } = msg;
delete msg.loggingLevel;

const messageToLog = `${formattedDateTime} - [info] [function:Log message to system console] ${JSON.stringify(msg)}`;

if (loggingLevel === 'error') {
  node.error(messageToLog);
  return;
}

node.log(messageToLog);

I work in a docker

If you want to get a formatted date, the easiest way is to use JSONata, in a change node for example, and use $moment() in your JSONata expression

change your tz accordingly

$moment().tz("Europe/London").format("YYYY:MM:DD HH:mm:ss")

image

Just add to @marcus-j-davies info.
You can use moments direct in the function node
e,g

[{"id":"436fe97ebbedc332","type":"inject","z":"d1395164b4eec73e","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":160,"y":1580,"wires":[["003f6421dba7fad7"]]},{"id":"003f6421dba7fad7","type":"function","z":"d1395164b4eec73e","name":"function 148","func":"\nreturn {payload: \nmoment.tz(\"Europe/London\").format(\"YYYY\")}","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"moment","module":"moment"},{"var":"momentTimezone","module":"moment-timezone"}],"x":350,"y":1580,"wires":[["1add159ae1ed848e"]]},{"id":"1add159ae1ed848e","type":"debug","z":"d1395164b4eec73e","name":"debug 2456","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":530,"y":1580,"wires":[]}]

You have to add moment and moment-timezone to the setup tab
and enable functionExternalModules in your setting file.
https://nodered.org/docs/user-guide/writing-functions#using-the-functionexternalmodules-option

Not sure how or if it would affect the log time format though, anyone else know?
[edit]
To log with adjusted timestamp use
console.log(moment.tz("Europe/London").format("YYYY-DD-MM HH:mm;ss"), "test")
more info here Logging : Node-RED

1 Like

And, of course, since you are using a modern Node.js, you don't need MomentJS at all for this, instead, the standard Date object formatting will do it just fine in a function node and will do local date/time formats too.

Just remember to think about whether you are using UTC (AKA Zulu or GMT) or using local timezones.

Yes of course, but moment makes the coding easier and more concise, in my opinion.

The standard Date object in CJS I think is terrible on its own!
its one of the most weak API's IMO.

I think my hatred towards it, is the fact its really not user friendly, and you end up with really ugly expressions to get what you want out of it.

I think the OP's attempt shows that

You need to use the INTL formatting options which let you do pretty much anything. But MomentJS is OK though it is no longer in production and is rather heavyweight just for date/time formatting.

Yup.

I think day.js is ā€œthe new kid on the blockā€ and replaces moment in a lot of frameworks I use.

I have not had much experience with it directly, but apparently is an almost drop in replacement.

If you use Moment.js, you already know how to use Day.js.

3 Likes

Agree. Would like to update node-red-contrib-moment to use it but just don't have the time.

Thanks for info about day.js

1 Like

i use day.js regulary. Example with Plugins:

[{"id":"9e0a19990afbd114","type":"function","z":"7636363de3130c9f","name":"day.js","func":"dayjs.extend(isBetween)\n\nconst now = dayjs()\nconst future = now.add(60,'second')\nconst between = now.add(30, 'second')\nlet calc_between = false\nlet new_payload = {}\n\nif (between.isBetween(now, future)) {\n    calc_between = true\n    }\n\n\nnew_payload['now'] = now\nnew_payload['now_formatted'] = now.format('YYYY-MM-DD HH:mm')\nnew_payload['future'] = future\nnew_payload['between'] = between\nnew_payload['calc_between'] = calc_between\n\n\n\nmsg.payload = new_payload\nreturn msg;","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"// Der Code hier wird ausgefĆ¼hrt,\n// wenn der Node gestoppt wird\nnode.status({fill:\"red\",shape:\"ring\",text:\"Waiting ... \"});","libs":[{"var":"dayjs","module":"dayjs"},{"var":"isBetween","module":"dayjs/plugin/isBetween"}],"x":630,"y":440,"wires":[["9618ddd0090b5fbe"]],"icon":"font-awesome/fa-calendar"},{"id":"d9b9a535ae3f139e","type":"inject","z":"7636363de3130c9f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":480,"y":440,"wires":[["9e0a19990afbd114"]]},{"id":"9618ddd0090b5fbe","type":"debug","z":"7636363de3130c9f","name":"debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":770,"y":440,"wires":[]}]

You don't need moment for this anymore as @TotallyInformation stated, it is part of javascript, moment is more convoluted imo.

const event = new Date('23 Nov 2023 17:45:00');
const jsonDate = event.toJSON();

node.warn(jsonDate);
// "2023-11-23T16:45:00.000Z" = UTC

node.warn(event.toLocaleString('en-GB', { timeZone: 'UTC' }));
// "23/11/2023, 16:45:00"

node.warn(event.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// "2023. 11. 23. ģ˜¤ķ›„ 4:45:00"

node.warn(event.toLocaleString('us-US', { timeZone: 'America/Los_Angeles' }));
// "11/23/2023, 8:45:00 AM"

Recommendation: always use ISO8601 notation in logs.

And always work in UTC except for user input and user display.

1 Like

Try formating to "YYYY:MM:DD HH:mm;ss" as OP wanted, you will find it more convoluted, in my opinion. I read what @TotallyInformation said, I do not agree, as I clearly stated. Telling me again has not changed my opinion. Moments and dayjs have more functionality to (add, subtract, diff , between, etc).

moment().utc().format("YYYY:MM:DD HH:mm:ss")

Not that convoluted.

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