Checking if two Dates have the same date info

后端 未结 8 586
清歌不尽
清歌不尽 2020-11-27 05:40

How can I check if two different date objects have the same date information(having same day, month, year ...)? I have tried "==", "===" and .equals but

相关标签:
8条回答
  • 2020-11-27 06:05

    subtract them and compare to zero:

    var date1 = new Date();
    var date2 = new Date();
    

    // do something with the dates...

    (date1 - date2) ? alert("not equal") : alert("equal");
    

    to put it into a variable:

    var datesAreSame = !(date1 - date2);
    
    0 讨论(0)
  • 2020-11-27 06:08

    Type convert to integers:

    a = new Date(1995,11,17);
    b = new Date(1995,11,17);
    +a === +b;  //true
    
    0 讨论(0)
  • 2020-11-27 06:12

    If you are only interested in checking if dates occur on the same day regardless of time then you can use the toDateString() method to compare. This method returns only the date without time:

    var start = new Date('2015-01-28T10:00:00Z');
    var end = new Date('2015-01-28T18:00:00Z');
    
    if (start.toDateString() === end.toDateString()) {
      // Same day - maybe different times
    } else {
      // Different day
    }
    
    0 讨论(0)
  • 2020-11-27 06:15

    I used this code:

    Date.prototype.isSameDateAs = function(pDate) {
      return (
        this.getFullYear() === pDate.getFullYear() &&
        this.getMonth() === pDate.getMonth() &&
        this.getDate() === pDate.getDate()
      );
    }
    

    Then you just call it like : if (aDate.isSameDateAs(otherDate)) { ... }

    0 讨论(0)
  • 2020-11-27 06:16

    For better date support use moment.js and isSame method

    var starDate = moment('2018-03-06').startOf('day');
    var endDate  = moment('2018-04-06').startOf('day');
    
    console.log(starDate.isSame(endDate)); // false ( month is different )
    
    var starDate = moment('2018-03-06').startOf('day');
    var endDate  = moment('2018-03-06').startOf('day');
    
    console.log(starDate.isSame(endDate)); // true ( year, month and day are the same )
    
    0 讨论(0)
  • 2020-11-27 06:28

    You can use valueOf() or getTime():

    a = new Date(1995,11,17);
    b = new Date(1995,11,17);
    
    a.getTime() === b.getTime() // prints true
    
    0 讨论(0)
提交回复
热议问题