小能豆

How do I get the current date in JavaScript?

javascript

How do I get the current date in JavaScript?


阅读 104

收藏
2023-12-02

共1个答案

小能豆

You can get the current date in JavaScript using the Date object. Here are a couple of ways to achieve this:

  1. Using new Date() constructor:

const currentDate = new Date(); console.log(currentDate);

The new Date() constructor without any arguments creates a Date object representing the current date and time.

  1. Using 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:

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.

2023-12-02