In this post, we'll look at how to get the current date, including the month, year, day, hour, minute, and seconds, in Node.
We'll also look at how to get the date and time formatted in the YYYY-MM-DD and YYYY-MM-DD HH:mm:ss formats. This will all be done in vanilla JavaScript, without any third-party libraries.
Get the Current Date and Time
In Node, you can get the current date and time using the JavaScript Date object. This is native to JavaScript and so comes with Node by default.
To get the current date and time, create a new Date object.
JAVASCRIPT
const now = newDate();
From here, you can call several methods on the Date object.
getDate(): Returns the day of the month (from 1 - 31)
getDay(): Returns the day of the week (from 0 - 6)
getMonth(): Returns the month (from 0 - 11)
getFullYear(): Returns the year (four digits)
getHours(): Returns the hour (from 0 - 23)
getMinutes(): Returns the minutes (from 0 - 59)
getSeconds(): Returns the seconds (from 0 - 59)
Format the Date and Time
Using the above methods, we can format the date and time in a variety of ways.
Here is how to format a date in the YYYY-MM-DD format.
JAVASCRIPT
const now = newDate();
const year = now.getFullYear();
const month = ("0" + (now.getMonth() + 1)).slice(-2);
const day = ("0" + now.getDate()).slice(-2);
// YYYY-MM-DDconst formatted = `${year}-${month}-${day}`;
Here is the same date and time formatted in the YYYY-MM-DD hh:mm:ss format.
Another way to get the current timestamp is to use the Date.now() method.
JAVASCRIPT
const timestamp = Date.now();
Get the Date and Time from Timestamp
Given a timestamp, you can pass it to the Date constructor to get a new Date object from it.
From there you can format the date object.
JAVASCRIPT
const now = newDate();
const milliseconds = now.getTime();
const date = newDate(milliseconds);
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
// YYYY-MM-DDconst formatted = `${year}-${month}-${day}`;
Conclusion
We've seen how to get the current date and time in Node. We've also seen how to format the date and time in any format you want, like YYYY-MM-DD and YYYY-MM-DD hh:mm:ss.
Hopefully, this post has been useful to you!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!