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 objectconst date = new Date();// get the current date from Date objectconst currDate = date.toLocaleDateString();// print on consoleconsole.log(currDate);
Explanation
- Line 2: We created a
Dateobject. - Line 5: We got the current date from the
Dateobject. - Line 8: We printed the current date on the console.
Note: To get the current date in yyyy-mm-dd format, we can use theDate().toISOString()method. It is very similar to theDate().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 objectconst date = new Date();// get the current date of the monthconst currDate = date.getDate();// get the current month of the yearconst currMonth = date.getMonth() + 1;// get the current yearconst currYear = date.getFullYear();// combine above fields to get current dateconst output = `${currMonth}/${currDate}/${currYear}`;// print on consoleconsole.log(output);
Explanation
- Line 2: We created a
Dateobject. - 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.