How to compare only the date with Date objects?

Asked

Viewed 238 times

2

I want to create a function group that compares dates in Typescript. So far I have the following:

function amanhaOuDepois(date: Date): boolean{
    if(date > (new Date()))
        return true;
    return false;
}

function ontemOuAntes(date: Date): boolean{
    if(date < (new Date()))
        return true;
    return false;
}

function hoje(date: Date): boolean{
    if(date == (new Date()))
        return true;
    return false;
}

All functions are working as expected, minus the function amanhaOuDepois, who always returns false. How can I compare only the date of a type object Date, ignoring the hour, minutes and seconds?

  • 2

    only one addendum: (date < (new Date())) this already returns true or false ... then just give one return date < new Date();

  • It was to make the code a little more readable hehehe, but yes, you’re right

  • 1

    Has two functions with the same name: amanhaOuDepois ... note this ... I think typo.

  • @Virgilionovic corrected, thank you

2 answers

2

Compare by method getTime() that returns the numeric value corresponding to the time of the specified date according to the universal time.

Example:


Class:

class DateTimeCompare {
  getDate(): Date {
    return new Date(new Date().toDateString());
  }
  getTime(): number {
    return this.getDate().getTime();
  }
  lessThan(date: Date): boolean {
    return date.getTime() < this.getTime();
  }
  moreThan(date: Date): boolean {
    return date.getTime() > this.getTime();
  }
  equal(date: Date): boolean {
    return date.getTime() === this.getTime();
  }
}

var dateEqualTrue = new Date(new Date().toDateString());
var dateEqualFalse = new Date();

var dateTimeCompare = new DateTimeCompare();
console.log(dateTimeCompare.equal(dateEqualTrue));  
console.log(dateTimeCompare.equal(dateEqualFalse));  

Reference:

2


If you reset the time part then only the date is left to compare. You can do this with setHours(). This way will be compared the timestamp only considering the part of the same date.

let date = new Date(2019, 11, 3);
console.log(date);
console.log(new Date());
console.log(date.setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0));

So on TS would look something like this:

function amanhaOuDepois(date: Date): boolean {
     return date.setHours(0, 0, 0, 0) > new Date().setHours(0, 0, 0, 0);
}
function ontemOuAntes(date: Date): boolean {
     return date.setHours(0, 0, 0, 0) < new Date().setHours(0, 0, 0, 0);
}
function hoje(date: Date): boolean {
     return date.setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0);
}

I put in the Github for future reference.

This does not consider time zone.

Consider using the library Moment.js to facilitate and be more reliable. It was prepared to handle time data more adequately than most programmers would. Works with Typescript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.