Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if ISO String date is between two dates

I want to check if the middle date is between the right and left date, how can I accomplish this in Javascript, they are an ISO String.

From 2021-01-30T05:00:00.000Z <-> Date 2021-01-31T22:18:46Z <-> To 2021-01-31T05:00:00.000Z

How can I verify 2021-01-31T22:18:46Z is between 2021-01-30T05:00:00.000Z and 2021-01-31T05:00:00.000Z

like image 454
Johnny Biy Avatar asked May 19 '26 21:05

Johnny Biy


1 Answers

Two easy options...

Compare the date strings lexicographically

const From = "2021-01-30T05:00:00.000Z"
const date = "2021-01-31T22:18:46Z"
const To   = "2021-01-31T05:00:00.000Z"

if (From.localeCompare(date) <= 0 && To.localeCompare(date) >= 0) {
  console.log("Date is in range")
} else {
  console.log("Date is not in range")
}

or parse the date strings as Date instances or timestamps and compare them numerically

const From = new Date("2021-01-30T05:00:00.000Z")
const date = new Date("2021-01-31T22:18:46Z")
const To   = new Date("2021-01-31T05:00:00.000Z")

if (From <= date && To >= date) {
  console.log("Date is in range")
} else {
  console.log("Date is not in range")
}

Note: If you're using Typescript, it doesn't like comparing Date instances numerically. Compare Date.prototype.valueOf() or Date.prototype.getTime() instead

like image 200
Phil Avatar answered May 22 '26 12:05

Phil