What is the simplest way to compare two dates neglecting the timestamps. I have got two dates firstDate
coming from the database (converted into javascript date) and secondDate
coming from a date picker input field.
Essentially for
my algorithm these two dates are equal as it doesn't take timestamp into consideration but the code won't consider it equal as firstDate
has 01:00:00
in it.
How to completely discard the timestamp for comparison?
firstDate:
Tue Mar 24 1992 01:00:00 GMT-0500 (Central Daylight Time)
secondDate:
Tue Mar 24 1992 00:00:00 GMT-0500 (Central Daylight Time)
Code:
if(firstDate < secondDate) {
alert("This alert shouldn't pop out as dates are equal");
}
If you want to compare just the date part without considering time, you need to use DateFormat class to format the date into some format and then compare their String value. Alternatively, you can use joda-time which provides a class LocalDate, which represents a Date without time, similar to Java 8's LocalDate class.
In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.
You could use toDateString
to get rid of the the time, and reassign that to the firstDate and secondDate variables. There might be a better way, but this is what came to mind for me.
firstDate = new Date(firstDate.toDateString());
secondDate = new Date(secondDate.toDateString());
if(firstDate < secondDate){
alert("This alert shouldn't pop out as dates are equal");
}
Also, you'll want to make sure you're comparing the values of the dates, and not checking if they're the same object when you compare if they're equal. So something like.
firstDate.valueOf() == secondDate.valueOf()
You can also check out my JSFiddle example.
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