How to check if input date is equal to today's date?

后端 未结 10 1005
忘了有多久
忘了有多久 2020-11-28 05:13

I have a form input with an id of \'date_trans\'. The format for that date input (which is validated server side) can be any of:

  • dd/mm/yyyy
  • dd-mm-yyyy
相关标签:
10条回答
  • 2020-11-28 05:18
    function sameDay( d1, d2 ){
      return d1.getUTCFullYear() == d2.getUTCFullYear() &&
             d1.getUTCMonth() == d2.getUTCMonth() &&
             d1.getUTCDate() == d2.getUTCDate();
    }
    
    if (sameDay( new Date(userString), new Date)){
      // ...
    }
    

    Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)

    0 讨论(0)
  • 2020-11-28 05:18

    The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.

    var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
    return reducedToDay(date1) == reducedToDay(date2)
    

    The tilde truncs the division result (see this article about integer division)

    0 讨论(0)
  • 2020-11-28 05:24

    for completeness, taken from this solution:

    You could use toDateString:

    var today = new Date();
    var isToday = (today.toDateString() == otherDate.toDateString());
    

    no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho

    0 讨论(0)
  • 2020-11-28 05:26

    Just use the following code in your javaScript:

    if(new Date(hireDate).getTime() > new Date().getTime())
    {
    //Date greater than today's date 
    }
    

    Change the condition according to your requirement.Here is one link for comparision compare in java script

    0 讨论(0)
  • 2020-11-28 05:27

    Try using moment.js

    moment('dd/mm/yyyy').isSame(Date.now(), 'day');
    

    You can replace 'day' string with 'year, month, minute' if you want.

    0 讨论(0)
  • 2020-11-28 05:29

    The Best way and recommended way of comparing date in typescript is:

    var today = new Date().getTime();
    var reqDateVar = new Date(somedate).getTime();
    
    if(today === reqDateVar){
     // NOW
    } else {
     // Some other time
    }
    
    0 讨论(0)
提交回复
热议问题