"The Definitive Guide to DateTime Manipulation" by Toptal

I’ve had a lot of “fun” with DateTime, formatting dates and time, timestamps recently and this article is the best resource I found:

Here is the snippet from the article which I use in a function node to format date time however I or a third party API needs it:
Note the pad function which adds a 0 to single digit month or dates (2021-5-9 becomes 2021-05-09). I name a lot of files with this format and was struggling before how to get it to work in JavaScript. The months start at 0

const now = new Date();

function pad(n) {
    return n<10 ? '0'+n : n
}

const localDateTime = now.getFullYear() +
                      "-" +
                      pad(now.getMonth()+1) +
                      "-" +
                      pad(now.getDate()) +
                      " " +
                      pad(now.getHours()) +
                      ":" +
                      pad(now.getMinutes()) +
                      ":" +
                      pad(now.getSeconds());


items[0].json.time = localDateTime
return items

I still have to understand how to master timezones but will get there eventually.

Best,
Chris

2 Likes

Thanks for sharing @chris. Have you tried the Date & Time node :eyes: ?

Yes, I have but it doesn’t cover all the cases I’ve had with date time. It is good for quick things, but when I’m testing and debugging then it doesn’t fit well into the workflow (e.g. adding or substracting a day requires me to reconfigure the whole node vs just adding ± 1 to the code). Also I tend to run into really weird timestamps occasionally (e.g. Webkit Version) which requires math to resolve. Better to do that with code as well.

Just adding this here, because it took me a good half hour to figure out how to parse and format a DateTime nicely within JS (and thus also within {{ ... }} in n8n):

DateTime.fromISO("2024-06-07T16:00").toFormat("dd DD")

And then formatters reference is here: luxon - Immutable date wrapper

Hi @xeruf
Thanks for sharing.

This topic is very old though and at that time there was no luxon in n8n expressions. :slight_smile:

Maybe good to go through these tips & tricks topics and see what needs updating/closing if no longer relevant. :thinking: