Comparing date part only without comparing time in JavaScript

后端 未结 22 1458
春和景丽
春和景丽 2020-11-22 10:59

What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn\'t

相关标签:
22条回答
  • 2020-11-22 11:56

    An efficient and correct way to compare dates is:

    Math.floor(date1.getTime() / 86400000) > Math.floor(date2.getTime() / 86400000);
    

    It ignores the time part, it works for different timezones, and you can compare for equality == too. 86400000 is the number of milliseconds in a day (= 24*60*60*1000).

    Beware that the equality operator == should never be used for comparing Date objects because it fails when you would expect an equality test to work because it is comparing two Date objects (and does not compare the two dates) e.g.:

    > date1;
    outputs: Thu Mar 08 2018 00:00:00 GMT+1300
    
    > date2;
    outputs: Thu Mar 08 2018 00:00:00 GMT+1300
    
    > date1 == date2;
    outputs: false
    
    > Math.floor(date1.getTime() / 86400000) == Math.floor(date2.getTime() / 86400000);
    outputs: true
    

    Notes: If you are comparing Date objects that have the time part set to zero, then you could use date1.getTime() == date2.getTime() but it is hardly worth the optimisation. You can use <, >, <=, or >= when comparing Date objects directly because these operators first convert the Date object by calling .valueOf() before the operator does the comparison.

    0 讨论(0)
  • 2020-11-22 11:56

    The date.js library is handy for these things. It makes all JS date-related scriping a lot easier.

    0 讨论(0)
  • 2020-11-22 11:56

    This works for me:

     export default (chosenDate) => {
      const now = new Date();
      const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
      const splitChosenDate = chosenDate.split('/');
    
      today.setHours(0, 0, 0, 0);
      const fromDate = today.getTime();
      const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();
    
      return toDate < fromDate;
    };
    

    In accepted answer, there is timezone issue and in the other time is not 00:00:00

    0 讨论(0)
  • 2020-11-22 11:57

    Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).

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