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