How to check date with current date using jQuery

前端 未结 6 1305
长情又很酷
长情又很酷 2020-12-11 08:27

I want to check my date is greater than current date

$(\"#EndDate\").val() =\"5/13/2014\" ->M/d/y

Please find below code



        
6条回答
  •  情歌与酒
    2020-12-11 09:18

    If:

    $("#EndDate").val();
    

    returns a string in m/d/y format, you can turn that into a date object using:

    function parseDate(s) {
      var b = s.split(/\D/);
      return new Date(b[2], --b[0], b[1]);
    }
    

    To create a comparable date, do what you are already doing:

    var today = new Date();
    today.setHours(0,0,0,0);
    

    So now you can do:

    if (parseDate($("#EndDate").val()) > today) {
      // date is greater than today
    }
    

    or if you really must:

    if (+parseDate($("#EndDate").val()) > new Date().setHours(0,0,0,0)) ...
    

    Please note that when you do:

    Date.parse(new Date().setHours(0, 0, 0, 0))
    

    firstly a new date is created from new Date(). Calling setHours() sets the time value, but the return value from the call is the UTC time value of the Date object.

    Date.parse expects a string that looks something like a date and time, so if you pass it a number time value something like 1399903200000, the implementation will fall back to some implementation heuristics to either turn it into a Date or NaN.

    So please don't do that. Parsing any string with Date.parse is implementation dependent (even the strings specified in ECMA5) and will return different results in different browsers. So please don't do that either.

提交回复
热议问题