I am using the following for a user to input a date in a form:
I am wondering if ther
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
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.
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 Date
s 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 :)