Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date comparison ignoring timestamp value

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");
    }
like image 646
user1195192 Avatar asked Feb 15 '12 20:02

user1195192


People also ask

How do you compare two dates without the time portion?

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.

Can you compare JavaScript dates?

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.


1 Answers

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.

like image 190
derekaug Avatar answered Sep 30 '22 00:09

derekaug