JavaScript Date getDate()
Syntax & Examples
getDate() method
The getDate() method of the Date object in JavaScript returns the day of the month (1 – 31) for the specified date according to local time.
Syntax of getDate()
The syntax of Date.getDate() method is:
getDate()
This getDate() method of Date returns the day of the month (1 – 31) for the specified date according to local time.
Return Type
Date.getDate() returns value of type Number
.
✐ Examples
1 Using getDate() to get the day of the month
In JavaScript, we can use the getDate()
method to get the day of the month from a Date object.
For example,
- We create a new Date object
date
representing January 15, 2021. - We use the
getDate()
method to get the day of the month fromdate
. - The day of the month is stored in the variable
day
. - We log
day
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2021-01-15');
const day = date.getDate();
console.log(day);
Output
15
2 Using getDate() with the current date
In JavaScript, we can use the getDate()
method to get the current day of the month from the current date.
For example,
- We create a new Date object
today
representing the current date. - We use the
getDate()
method to get the current day of the month fromtoday
. - The current day of the month is stored in the variable
currentDay
. - We log
currentDay
to the console usingconsole.log()
method.
JavaScript Program
const today = new Date();
const currentDay = today.getDate();
console.log(currentDay);
Output
31
3 Using getDate() with a specific date in the past
In JavaScript, we can use the getDate()
method to get the day of the month from a specific date in the past.
For example,
- We create a new Date object
pastDate
representing July 4, 1776. - We use the
getDate()
method to get the day of the month frompastDate
. - The day of the month is stored in the variable
pastDay
. - We log
pastDay
to the console usingconsole.log()
method.
JavaScript Program
const pastDate = new Date('1776-07-04');
const pastDay = pastDate.getDate();
console.log(pastDay);
Output
4
Summary
In this JavaScript tutorial, we learned about getDate() method of Date: the syntax and few working examples with output and detailed explanation for each example.