Use Inbuilt Method
In this approach, we get different parts of a date using their respective methods. The date is extracted using
getDate(), the month is extracted using
getMonth() and the year is extracted using the
getYear() method. The month extracted is
0 indexed, so we need to add
1 to get the current month. The single-digit day and month can be padded with
0 to make them both
2 digits. We then concatenate results from all
3 parts to obtain the final date.
let date = new Date(); let output = String(date.getDate()).padStart(2, '0') + '/' + String(date.getMonth() + 1).padStart(2, '0') + '/' + date.getFullYear(); console.log(output);
toDateString() method returns the day and date part of a Date object. The return type is a string that consists of
3 letters specifying day,
3 letters specifying month, followed by day and date in numeric format. This method is very convenient compared to the above method, where we have to use a separate function to get the date, month, and year. But if we want the date in the numeric format, then this method is not of much help.
let date = new Date().toDateString(); console.log(date);
"Mon Jun 14 2021"
This method is used to return the date and time in ISO 8601 format. It usually returns the output in 24 characters long format such as
YYYY-MM-DDTHH:mm:ss.sssZ. We can notice that the date and time are separated from each other by the letter
T. So, if we split the ISO Date/Time String by T, we get two strings, one containing the date and the other containing the time. This way, we can get the current date from the ISO string. The one thing untypical is that the output is separated by
- instead of
/. So, one should use a different method as per requirement.
let date = new Date(); console.log(date.toISOString().split('T'));
Use Inbuilt Method
This function is intended to get the language-sensitive date portion of the
Date object. The locale argument specifies the language tag and the country, and options help to customize it further. But we can also use it to get the current date from the
Date object simply.
let date = new Date(); console.log(date.toLocaleDateString());