Jake Chasan
Jake Chasan

Reputation: 6550

Parse Date, Month, and Year from Javascript "Date" form

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

<input name="name" type="date" id="id"/>

I am wondering if there is a way to parse the Day, Month, and Year from this and set them into different variables. I am trying to use only Javascript, not PHP.

The 3 variables would be integers.

Thanks.

Upvotes: 4

Views: 32558

Answers (4)

Melisa M.
Melisa M.

Reputation: 121

Regular expression improvements with ES9. You can use like that.

const  
reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/,
match = reDate.exec('2019-05-29'),
year = match[1],  //2019
month = match[2], //05
day = match[3];   //29

Upvotes: 0

Brian North
Brian North

Reputation: 1398

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 :)

Upvotes: 7

Erin Stanfill
Erin Stanfill

Reputation: 1278

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

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

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.

Upvotes: 1

Related Questions