How to get day name from Date in JavaScript
Today, you will learn how to get day name from date in JavaScript.
Sometimes we need to show the day’s name based on the given date. In the Ecommerce website, when an order is placed, you may see the approximate shipment day.
Using the JavaScript date object along with two methods date.toLocaleString() and date.getDay(), we can easily get the day of the week.
- Show/Hide Text Box using JavaScript and jQuery
- How to get last N elements of an array in JavaScript
- Get today’s, tomorrow’s and yesterday’s date using JavaScript
- 5 Awesome JavaScript String Tips
- Calculate age using JavaScript
1. toLocaleString() method
JavaScript date object’s toLocaleString()
provides various properties with which you can extract information related to a date in any format.
// Get current day
var dateObj = new Date()
var weekday = dateObj.toLocaleString("default", { weekday: "long" })
console.log(weekday);
// Output: Friday
// Get day name from given date
var dateObj = new Date('2021-01-21')
var weekday = dateObj.toLocaleString("default", { weekday: "short" })
console.log(weekday);
// Output: Thursday
You can also get the short day format using short
in the second argument as shown below.
var dateObj = new Date()
var weekday = dateObj.toLocaleString("default", { weekday: "short" })
console.log(weekday);
// Output: Fri
2. getDay() method
The getDay()
method returns an integer representing the day of the week. (0 for sunday up to 6 for saturday)
var dateObj = new Date()
var weekdayNum = dateObj.getDay();
console.log(weekdayNum);
// Output: 5
Here, using the getDay()
method, we can get the zero-based number value of the current weekday.
To get the name of day, we need to create an array of day strings which corresponds to the numeric value of the weekdayNum
. Let’s check with an example.
var daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// Get current day
var dateObj = new Date();
var weekdayNum = dateObj.getDay();
var weekday = daysArray[weekdayNum];
console.log(weekday);
// Output: Friday
// Get day name from given date
var dateObj = new Date('2021-01-21');
var weekdayNum = dateObj.getDay();
var weekday = daysArray[weekdayNum];
console.log(weekday);
// Output: Thursday
That’s it for today.
Thank you for reading. Happy Coding..!!