how to get datetime in nodejs
To get the current date and time in Node.js, you can use the built-in Date
object. Here are the steps to do it:
Create a new instance of the
Date
object:javascript const currentDate = new Date();
Extract the desired information from the
Date
object:- To get the current date, you can use the
getDate()
,getMonth()
, andgetFullYear()
methods:javascript const day = currentDate.getDate(); const month = currentDate.getMonth() + 1; // Note: Months are zero-based const year = currentDate.getFullYear();
To get the current time, you can use the
getHours()
,getMinutes()
, andgetSeconds()
methods:javascript const hours = currentDate.getHours(); const minutes = currentDate.getMinutes(); const seconds = currentDate.getSeconds();
Format the extracted information as desired:
If you want to display the date and time in a specific format, you can concatenate the extracted information and add any necessary separators. For example, to display the date and time in the format "YYYY-MM-DD HH:MM:SS":
javascript const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
Use the formatted date and time as needed in your application.
That's it! You now have the current date and time in Node.js.