Check if Date Is Between Two Dates

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to check if a date falls between two other dates using JavaScript. We will use the greater than and less than operators to compare the dates and return a boolean value indicating if the date is between the start and end dates. This technique can be useful in various scenarios such as filtering data based on a date range.


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-28244{{"`Check if Date Is Between Two Dates`"}} javascript/data_types -.-> lab-28244{{"`Check if Date Is Between Two Dates`"}} javascript/arith_ops -.-> lab-28244{{"`Check if Date Is Between Two Dates`"}} javascript/comp_ops -.-> lab-28244{{"`Check if Date Is Between Two Dates`"}} end

Checking if a Date is Between Two Dates

To check if a date is between two other dates, use the greater than (>) and less than (<) operators in JavaScript. Here's an example function:

const isBetweenDates = (dateStart, dateEnd, date) =>
  date > dateStart && date < dateEnd;

To use this function, pass in the start date, end date, and date to check. The function will return true if the date is between the start and end dates, and false otherwise. Here are some examples:

isBetweenDates(
  new Date(2010, 11, 20),
  new Date(2010, 11, 30),
  new Date(2010, 11, 19)
); // false

isBetweenDates(
  new Date(2010, 11, 20),
  new Date(2010, 11, 30),
  new Date(2010, 11, 25)
); // true

To start practicing coding, open the Terminal/SSH and type node.

Summary

Congratulations! You have completed the Check if Date Is Between Two Dates lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like