Quick Tip: How I Compare Dates Properly in React (JavaScript Date Gotcha)
So I am building a todo app(very common, I know), and in that, there must be a feature for due dates. Due dates are a must, in the sense that they provide a deadline for when the task must be completed.
I implemented a color based system to differentiate whether a task is
currently active (due date is in future): denoted by green color,
same day (due date is the same as creation): denoted by orange,
overdue (due date is over): denoted by red and an overdue indicator
I implemented it and it worked alright but I saw that the task created today also had an overdue indicator.
I thought, what’s happening here, and then I realized the time factor is involved in the comparison, if you compare two date objects there always be time involved and it will not be desired in every case (like my case)
const compareDate = (date) => {
const current = new Date()
const due = new Date(date)
if(current === due) return 'orange'
if(current > due) return 'red' //here basically
return 'green'
}
But if you use .toDateString() to compare only date will be compared and time factor is eliminated:
const compareDate = (date) => {
const current = new Date()
const due = new Date(date)
if(current.toDateString() === due.toDateString()) return 'orange'
if(current > due) return 'red'
return 'green'
}
This fixed the problem for me, so if you’re facing the same problem and this helps, you can follow for more dev tips just like this!