How to Get Day of Week in JavaScript?
While learning JavaScript you might have stumbled across how to get name of the week day e.g. “Sunday” “Monday” etc from a date. In this article we will learn to get the day name of the week in short and long format.
Date API 💻
JavaScript date api provides getDay()
method to get the week day index of a date instance. It returns a zero based integer from 0-6
specifying the day of week for the given date.
0
means Sunday1
means Monday and so on.
|
|
The above code returns integer between 0-6 but we are interested in textual representation of day name e.g. Monday
or Mon
.
The traditional way 🧓
We know getDay()
returns integer between 0-6 where 0 means Sunday
. Hence we can define an array of week day names and make use of index returned by getDay()
.
|
|
The above code works undoubtedly, however the new Intl
API provides a better solution.
The modern way 😎
Intl.DateTimeFormat
provides a robust way to format date and times in different locales. The constructor accepts two optional params Intl.DateTimeFormat(locale, options)
. The second param options
accepts a variety of fields out of which we are interested in weekday
. You can pass one out of three (long
, short
, narrow
) values to weekday
.
{ weekday: "long" }
Full textual representation of week day e.g.Sunday
Monday
etc.{ weekday: "short" }
Short textual representation of week day e.g.Sun
Mon
etc.{ weekday: "narrow" }
Initials of week day e.g.S
M
etc. Note: Use it with caution it may result in same result for week days with same initials e.g. Sunday and Saturday for both it representsS
.
|
|
Weekday in different locale 🌐
The Intl.DateTimeFormat
simplifies the job a lot. You can use the API to get week day name in different locales (hindi, tamil etc.) too. Pass the desired locale in which you want week day name to the Intl.DateTimeFormat()
constructor.
|
|
References
Happy Coding 👨💻