Checking if two Dates have the same date info

后端 未结 8 587
清歌不尽
清歌不尽 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:30

    Hellnar,

    you could try (pardon the function name :) - amended per felix's valueof, rather than getTime)

    function isEqual(startDate, endDate) {
        return endDate.valueOf() == startDate.valueOf();
    }
    

    usage:

    if(isEqual(date1, date2)){
       // do something
    }
    

    might get you part of the way there.

    see also:

    'http://www.java2s.com/Tutorial/JavaScript/0240__Date/DatevalueOf.htm'

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

    A simple single line alternative for determining if two dates are equal, ignoring the time part:

    function isSameDate(a, b) {
        return Math.abs(a - b) < (1000 * 3600 * 24) && a.getDay() === b.getDay();
    }
    

    It determines if dates a and b differ no more than one day and share the same day of the week.

    function isSameDate(a, b) {
        return Math.abs(a - b) < (1000 * 3600 * 24) && a.getDay() === b.getDay();
    }
    
    console.log(isSameDate(new Date(2017, 7, 21), new Date(2017, 7, 21))); //exact same date => true
    console.log(isSameDate(new Date(2017, 7, 21, 23, 59, 59), new Date(2017, 7, 21))); //furthest same dates => true
    console.log(isSameDate(new Date(2017, 7, 20, 23, 59, 59), new Date(2017, 7, 21))); //nearest different dates => false
    console.log(isSameDate(new Date(2016, 7, 21), new Date(2017, 7, 21))); //different year => false
    console.log(isSameDate(new Date(2017, 8, 21), new Date(2017, 7, 21))); //different month => false

    0 讨论(0)
提交回复
热议问题