Home > database >  Compare yyyy-mm-dd formatted date strings without the Date object possible?
Compare yyyy-mm-dd formatted date strings without the Date object possible?

Time:12-13

If I define a date range using purely date strings in yyyy-mm-dd format, it appears comparision will work just fine without using the Date object:

const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts.slice(0, 1) // '2021-12-15'
const endDate = dateParts.slice(1) // '2022-01-15'

const date = '2021-12-14'

// Test if date is within the range     
console.log(date >= startDate && date <= endDate) // false

Using any date in the above example will test successfully if what I want is ensure that the date I'm looking for is within the range.

Why is this working? If javascript was, under the hood, evaluating the date strings as numbers, this should not be working. Is it maybe just implicitly assuming it's a date without me having to parse them using new Date(date)...?

Update: I'm not looking for solutions on how to do this using the Date object, I'd be more interested in examples where comparing dates this way would NOT work.

CodePudding user response:

Your code works (Or if it looks like its working) because its just a basic string comparison and not the date comparison. To do a proper date comparison, you need to do the proper string to date conversion, and then compare them.

const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts[0] // '2021-12-15'
const endDate = dateParts[1] // '2022-01-15'

const startDateArray = startDate.split("-").map(element => parseInt(element));
const endDateArray = endDate.split("-").map(element => parseInt(element));

const date = '2022-01-15'
const dateArray = date.split("-").map(element => parseInt(element));

// Test if date is within the range     
console.log(new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) >= new Date(startDateArray[0], startDateArray[1] - 1, startDateArray[2]) && new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) <= new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2])) // false

CodePudding user response:

This should solve your problem

const dateParts = '2021-12-15--2022-01-15'.split('--'); // My date range
const startDate = dateParts[1]; // '2021-12-15'
const endDate = dateParts[0]; // '2022-01-15'

const date = '2021-12-10'

// Test if date is within the range     
alert(date < startDate && date < endDate)

  • Related