How do I get the current date in JavaScript?
You can get the current date in JavaScript using the Date object. Here are a couple of ways to achieve this:
Date
new Date()
const currentDate = new Date(); console.log(currentDate);
The new Date() constructor without any arguments creates a Date object representing the current date and time.
Date.now()
const currentDateMillis = Date.now(); const currentDate = new Date(currentDateMillis); console.log(currentDate);
The Date.now() method returns the current timestamp in milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). You can pass this value to the Date constructor to get the current date.
Once you have the Date object, you can extract various components of the date such as the year, month, day, hours, minutes, and seconds using the corresponding get methods:
get
const year = currentDate.getFullYear(); const month = currentDate.getMonth() + 1; // Months are zero-based, so add 1 const day = currentDate.getDate(); const hours = currentDate.getHours(); const minutes = currentDate.getMinutes(); const seconds = currentDate.getSeconds(); console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
This will log the current date and time in the format: YYYY-MM-DD HH:mm:ss. Adjust the format as needed based on your requirements.
YYYY-MM-DD HH:mm:ss