Date Is Weekday

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will dive into JavaScript programming and learn how to work with dates and weekdays. Specifically, we will explore how to use the Date object in JavaScript to check whether a given date is a weekday or not. By the end of this lab, you will be able to write a function that determines if a date is a weekday or not, based on the day of the week.


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`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") subgraph Lab Skills javascript/variables -.-> lab-28246{{"`Date Is Weekday`"}} javascript/data_types -.-> lab-28246{{"`Date Is Weekday`"}} javascript/arith_ops -.-> lab-28246{{"`Date Is Weekday`"}} javascript/comp_ops -.-> lab-28246{{"`Date Is Weekday`"}} javascript/cond_stmts -.-> lab-28246{{"`Date Is Weekday`"}} end

Check if a Date is a Weekday

To check if a given date is a weekday, you can use the following code snippet:

const isWeekday = (date = new Date()) => date.getDay() % 6 !== 0;
  • This function uses Date.prototype.getDay() to get the day of the week as a number (0-6), where Sunday is 0 and Saturday is 6.
  • It then checks if the day of the week is not equal to 0 (Sunday) or 6 (Saturday), which means it is a weekday.
  • If no date is provided as an argument, the current date is used as the default.

Example usage:

isWeekday(); // true (if current date is a weekday)
isWeekday(new Date(2021, 5, 28)); // true (if date is a weekday)

Summary

Congratulations! You have completed the Date Is Weekday lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like