How to get the current date in JavaScript

In JavaScript, we can get the current date using the following methods:

  • Using Date().toLocaleDateString().
  • Using individual methods to find the year, month, and date.

Using Date().toLocaleDateString()

The Date().toLocaleDateString() method is used to return only the date portion of the Date() object. The format of the date is mm/dd/yyyy.

Syntax

Date().toLocaleDateString();
Syntax of toLocaleDateString()

Parameters

This method doesn't accept any parameters.

Return value

This method returns the current date.

Example

Let's see an example of the Date().toLocaleDateString() method in the code snippet below:

// create a Date object
const date = new Date();
// get the current date from Date object
const currDate = date.toLocaleDateString();
// print on console
console.log(currDate);

Explanation

  • Line 2: We created a Date object.
  • Line 5: We got the current date from the Date object.
  • Line 8: We printed the current date on the console.
Note: To get the current date in yyyy-mm-dd format, we can use the Date().toISOString() method. It is very similar to the Date().toLocaleDateString() method.

Using individual methods

We can get the current date of the month, current month of the year, and current year using the getDate(), getMonth(), and the getFullYear() method respectively on the Date() object.

We can then combine them together to get the current date.

Example

Let's see an example to get the current date using individual methods in the code snippet below:

// create a Date object
const date = new Date();
// get the current date of the month
const currDate = date.getDate();
// get the current month of the year
const currMonth = date.getMonth() + 1;
// get the current year
const currYear = date.getFullYear();
// combine above fields to get current date
const output = `${currMonth}/${currDate}/${currYear}`;
// print on console
console.log(output);

Explanation

  • Line 2: We created a Date object.
  • Line 5: We got the current date of the month using the getDate() method.
  • Line 8: We got the current month of the year using the getMonth() method.
  • Line 11: We got the current year using the getFullYear() method.
  • Line 14: We created the current date by combining the date, month, and year.
  • Line 17: We printed the current date on the console.

    Free Resources