JavaScript provides the Date object to access the current date and time. The toDateString() method can be used to get only the date portion as a readable string.
- Use new Date() to create an object containing the current date and time.
- Use toDateString() to convert the date into a readable date string.
- Use getDate(), getMonth(), and getFullYear() to extract individual date components.
Approach 1: Using toDateString() Method
The toDateString() method returns the date portion of a Date object as a readable string, without the time information.
Syntax:
dateObj.toDateString()Example: In this example, we create a Date object and use toDateString() to get the current date as a string.
// Create a Date Object
let d = new Date();
let d1 = d.toDateString();
console.log(d1);
Approach 2: Using the Date Object Directly
The Date constructor returns an object containing the current date and time when called without arguments. When logged, it displays the complete date and time representation.
Example: In this example, we create a Date object and display it directly.
// Create a Date Object
let d = new Date();
console.log(d);
Approach 3: Extracting Day, Month, and Year from the Date Object
Individual components of the current date can be extracted using the Date object's methods.
- The getDate() method returns the day of the month.
- The getMonth() method returns the month from 0 to 11, so 1 is added to get the usual month number.
- The getFullYear() method returns the four-digit year.
Example: In this example, we extract the current day, month, and year and combine them into DD/MM/YYYY format
let d = new Date();
let day = String(d.getDate()).padStart(2, "0");
let month = String(d.getMonth() + 1).padStart(2, "0");
let year = d.getFullYear();
let d1 = day + "/" + month + "/" + year;
console.log(d1);