masu9
masu9

Reputation: 511

How to tell if two dates are equal while ignoring time?

I want to compare two dates to see if they are the same, while ignoring Time as well.

I've tried using the .setHours(0,0,0,0) method to set the time to something neutral, but then I can't use the .getTime() method due to this error.. Property 'getTime' does not exist on type 'number'

I've also researched that I shouldn't use ===, but I can't overcome the getTime problem first.

if (this.datelist.filter(x => new Date (x.sentDate).setHours(0,0,0,0).getTime() === this.searchQuery.getTime()).length == 0) {
    console.log("No matches");
}

Upvotes: 1

Views: 249

Answers (3)

Nocturnal
Nocturnal

Reputation: 2037

I strongly recommend Moment.js for these kind of date operations. It is so much easier with Moment.js

moment('2019-04-25').isSame('2019-04-25'); // true

There are format methods available to covert the date to YYYY-MM-DD before comparing.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

The Date#setHours method already returns the time in a millisecond so you cant use Date#getTime method on a Number.

Since Date#setHours method already returns the time you can simply ignore the Date#getTime method and compare with the returned value.

if (this.datelist.filter(x => new Date(x.sentDate).setHours(0,0,0,0) === this.searchQuery.getTime()).length == 0) {
    console.log("No matches");
}


For this purpose, you can use Array#every method instead of Array#fileter method.

if (this.datelist.every(x => new Date(x.sentDate).setHours(0,0,0,0) !== this.searchQuery.getTime())) {
    console.log("No matches");
}

Upvotes: 0

Francisco Santorelli
Francisco Santorelli

Reputation: 1338

Your problem is the concatenation of methods.

When you have thing.methodA().methodB(), methodB will work with whatever returns from methodA, and in this case, setHours returns a time BUT in miliseconds from the baseDate, which is a number, and has no getTime() method.

Your solution is using the setHours in both objects after copying them, that'd be:

if (this.datelist.filter(x => new Date (x.sentDate).setHours(0,0,0,0) === this.searchQuery.setHours(0,0,0,0)).length === 0) {
    console.log("nope!");
}

also note that '===' should be used in all cases always except when checking empty values (you use val == null).

cheers!

Upvotes: 0

Related Questions