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

后端 未结 10 1006
忘了有多久
忘了有多久 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:33

    Date.js is a handy library for manipulating and formatting dates. It can help in this situation.

    0 讨论(0)
  • A simple date comparison in pure JS should be sufficient:

    // Create date from input value
    var inputDate = new Date("11/21/2011");
    
    // Get today's date
    var todaysDate = new Date();
    
    // call setHours to take the time out of the comparison
    if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
        // Date equals today's date
    }
    

    Here's a working JSFiddle.

    0 讨论(0)
  • 2020-11-28 05:42
    TodayDate = new Date();
    if (TodayDate > AnotherDate) {} else{}
    

    < = also works, Although with =, it might have to match the milliseconds.

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

    There is a simpler solution

    if (inputDate.getDate() === todayDate.getDate()) {
       // do stuff
    }
    

    like that you don't loose the time attached to inputDate if any

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