Retrieve Weekday Name Using JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28251{{"`Retrieve Weekday Name Using JavaScript`"}} javascript/data_types -.-> lab-28251{{"`Retrieve Weekday Name Using JavaScript`"}} javascript/arith_ops -.-> lab-28251{{"`Retrieve Weekday Name Using JavaScript`"}} javascript/comp_ops -.-> lab-28251{{"`Retrieve Weekday Name Using JavaScript`"}} end

Retrieving Day Name from a Date Object

To retrieve the name of the weekday from a Date object, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Date.prototype.toLocaleDateString() with the { weekday: 'long' } option to retrieve the weekday.
  3. 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.

Other JavaScript Tutorials you may like