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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With