Convert Javascript string to date

This question already has an answer here:

  • Why does Date.parse give incorrect results? 10 answers

  • You can "restrict" what the client input will be using JavaScript, to make sure that the data being entered is numeric, for example. With that numeric input, you can quite easily build a string in the desired format.
    I've set up this fiddle , with, pretty much, the same code, as the one below. the fiddle also does some basic checks (like not accepting dates à la 33/54/1001), and parses the Date, too. As soon as a full date is entered, click the button and check the output in your console: it's a regular date object, which can be compared to another date object (like that of today: curdate = new Date(); ).
    But in order for you to get started, here's a simplified version of the keypress handler, that deals with user input:

    var keypress = function(e)
    {
        e = e || window.event;//FROM HERE
        var el = e.target || e.srcElement,
        char = String.fromCharCode(e.keyCode || e.which);
        e.returnValue = false;
        e.cancelBubble = true;
        if (e.preventDefault)
        {
            e.preventDefault();
            e.stopPropagation();
        }//TO HERE, a lot of X-browser issues are adressed
        if (char == +(char) && el.value.length < 10)
        {//format input:
            el.value = (el.value + char).replace(/^([0-9]{0,2})/*([0-9]{0,2})/*([0-9]{0,4})$/,function(all, m, d, y)
             {
                 m += m.length === 2 ? '/' : '';
                 d += d.length === 2 ? '/' : '';
                 return m+d+y;
             });
        }
        return e;//done
    };
    var dateIn = document.getElementById('dateInputElement');
    if (dateIn.addEventListener)
    {//add event handlers
        dateIn.addEventListener('keypress',keypress, false);
    }
    else
    {
        return dateIn.attachEvent('onkeypress',keypress);
    }
    

    To get a better understanding of this code, you might want to take a look here and here.


    You can use a library like Date.js to parse user entered strings and other date-like values into a known format. Then compare directly.

    if (Date.parse(sdate) > Date.parse(curdate)) {
      ...
    }
    

    Using moment.js, you can do things like:

    if (moment(sdate, 'MM/DD/YYYY') > moment(curdate))
    ...
    

    If you are saying that curdate is representing "now", then just do:

    if (moment(sdate, 'MM/DD/YYYY') > moment())
    ...
    

    If you want to ensure that the date is in a particular format, you can use their validation functions:

    if (moment(sdate, 'MM/DD/YYYY').isValid())
    ...
    
    链接地址: http://www.djcxy.com/p/18622.html

    上一篇: JavaScript的日期是休息一天?

    下一篇: 将JavaScript字符串转换为日期