Date input in jQuery

Asked

Viewed 437 times

0

I am looking for a simple way to get the values of day, month and year separated from one input of the kind date, in jQuery.

$( "#ano" ).html($( "input[type=date]" ).val(  ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" value="2018-10-17">
<div id="ano"></div>

How do I get separate values without using split()?

1 answer

0


jQuery itself, as far as I know, has no method for this. What you can do is convert the field value to the object Date() Javascript and take the values. Just replace the hyphens with commas and take the values.

The string should be a format recognised by the method Date.parse() (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

var input = $("input[type=date]").val().replace(/-/g, ",");
var data = new Date(input);
$( "#ano" ).html( data.getFullYear() );
$( "#mes" ).html( data.getMonth()+1 );
$( "#dia" ).html( data.getDate() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" value="2018-10-17">
<div id="ano"></div>
<div id="mes"></div>
<div id="dia"></div>

It is necessary to add +1 in the value of the month because Javascript counts the months from the 0: January = 0, February = 1 etc.

  • Why you have to add +1 in the month?

  • 1

    I put in answer friend.

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.