4

I'm using an HTML input field of a date:

<input id="datepicker" type="date" value="11/12/2013" />

How can I get using JQuery the different values for the year, month and day? each one need to be save as a different var

Thanks,

user2828251
  • 235
  • 2
  • 7
  • 21
  • 2
    The value is just a string. Declaring `type="date"` doesn't cause it to be parsed automatically. jQuery has no functions for processing dates. You could try Moment.js, though. – Barmar May 31 '14 at 15:47
  • There is [`valueAsDate`](http://www.w3.org/TR/html5/forms.html#dom-input-valueasdate) though, but I haven’t checked how widely that is implemented … – CBroe May 31 '14 at 15:57

4 Answers4

2

You can use split by / to get them in array individually:

var date=$('#datepicker').val().split('/');
var day=date[0];
var month=date[1];
var year=date[2];
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

EDIT: For this to work you need to change type="text" OR you look at this post: set date in input type date

   var d = $('#datepicker').val().split('/');
    var year = d[2];
    var month = d[1];
    var day = d[0];

Supposing you are using the DD/MM/YYYY format.

Community
  • 1
  • 1
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

try like this:

Html:

<input id="datepicker" type="date" value="2013-11-11" />

JavaScript:

var date = $('#datepicker').val().split('-');
var year = date[2];
var month = date[1];
var day = date[0];

Note: type date take value in yyyy-mm-dd format

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
1

With Javascript es6 you can do a one-liner

let [day,month,year] = $('#datepicker').val().split('-');

Leon
  • 5,701
  • 3
  • 38
  • 38