Parse Date, Month, and Year from Javascript “Date” form

后端 未结 3 1712
后悔当初
后悔当初 2020-12-10 10:16

I am using the following for a user to input a date in a form:


I am wondering if ther

相关标签:
3条回答
  • 2020-12-10 10:32

    You will want to split the value on '-', not '/'. E.g.,

    $( "input" ).change(function(e) {
       var vals = e.target.value.split('-');
       var year = vals[0];
       var month = vals[1];
       var day = vals[2];
       console.info(day, month, year);
    });
    

    Here is a jsbin of a working example: http://jsbin.com/ayAjufo/2/edit

    0 讨论(0)
  • 2020-12-10 10:37

    You may try like this:-

    function parseDate(input) {
      var str= input.split('/');
      return new Date(str[0], str[1]-1, str[2]); 
    }
    

    str[1]-1 as months start from 0.

    You may also check Date.parse(string) but this implemetation dependent.

    0 讨论(0)
  • 2020-12-10 10:44

    Your best option, if you're accepting input and converting it to a date, either split by part or as a Date object, is to simply construct a new Date object by passing it the input value:

    var input = document.getElementById( 'id' ).value;
    var d = new Date( input );
    
    if ( !!d.valueOf() ) { // Valid date
        year = d.getFullYear();
        month = d.getMonth();
        day = d.getDate();
    } else { /* Invalid date */ }
    

    This way you can leverage Dates handling of multiple input formats - it will take YYYY/MM/DD, YYYY-MM-DD, MM/DD/YYYY, even full text dates ( 'October 25, 2013' ), etc. without having you write your own parser. Valid dates are then easily checked by !!d.valueOf() - true if it's good, false if not :)

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