Introduction
In this lab, we will explore how to retrieve the name of the weekday from a given date object using JavaScript. We will use the Date.prototype.toLocaleDateString() method with the { weekday: 'long' } option to get the weekday name. Additionally, we can specify a language-specific name using the optional second argument or use the default locale.
Retrieving Day Name from a Date Object
To retrieve the name of the weekday from a Date object, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Date.prototype.toLocaleDateString()with the{ weekday: 'long' }option to retrieve the weekday. - You can use the optional second argument to get a language-specific name or omit it to use the default locale.
Here's an example implementation:
const dayName = (date, locale) =>
date.toLocaleDateString(locale, { weekday: "long" });
You can use this function like this:
dayName(new Date()); // 'Saturday'
dayName(new Date("09/23/2020"), "de-DE"); // 'Samstag'
Summary
Congratulations! You have completed the Day Name lab. You can practice more labs in LabEx to improve your skills.