The getDate()
method is a built-in JavaScript function that is used to get the day of the month from a Date
object. It returns the numerical value of the day (from 1 to 31) as per the local time zone.
Here’s the basic syntax of the getDate()
method:
dateObject.getDate()
The dateObject
is an instance of the Date
object, and you call the getDate()
method on that object to retrieve the day of the month.
Here’s an example that demonstrates the usage of the getDate()
method:
const today = new Date();
const dayOfMonth = today.getDate();
console.log(dayOfMonth);
JavaScript getDate Method examples
Simple example code that demonstrates the usage of the getDate()
method in JavaScript:
// Create a new Date object
const date = new Date();
// Get the day of the month using getDate()
const dayOfMonth = date.getDate();
// Display the result
console.log("Today is the " + dayOfMonth + getOrdinalSuffix(dayOfMonth) + " of the month.");
// Function to get the ordinal suffix for a number
function getOrdinalSuffix(day) {
const suffixes = ["th", "st", "nd", "rd"];
const relevantDigits = (day < 30) ? day % 20 : day % 30;
const suffix = (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
return suffix;
}
Output:
Note: the getDate()
method returns the day of the month according to the local time zone, so the result may vary depending on your system’s settings.
Comment if you have any doubts or suggestions on this Js Date object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version