How to get only the day/month/year separately from an Input Date

Asked

Viewed 63 times

-3

I’m learning and trying to make a program that calculates the exact day a person was born. For this I created a date form on and he returns me for example: 2010-06-21... In order for me to calculate the exact day of the person’s birth, I need to take it separately input:date the day/month/year and put them in a variable. I have tried several ways and could not, can anyone help me? My code is like this:

function calcular (){
    var d = document.querySelector('input#data').value
    alert(d)
}
    <!DOCTYPE html>
    <html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Modelo de exercicio</title>
        <link rel="stylesheet" href="estilo.css">
    </head>
    <body>
        <header>
            <h4>Descubra o dia da semana que você nasceu</h4>
        </header>
        <section>
            <div id = 'primeiro'>
               Coloque sua data de nascimento
            </div>
            <br>
            <input type="date" name="data" id="data">
            <input type="button" name = 'botao' id='botao' value="Calcular" onclick="calcular()">
            <div>
                .
            </div>
        </section>
        <footer>
            <p>&copy; CursoemVideo</p>
        </footer>
    </body>
    </html>

1 answer

-3


The value of a single element <input> is always a string, in case of a date, it comes in the format YYYY-MM-DD (year-month-day).

You can separate the string using the character - as a separator, or else use the methods of an object of type Date to recover the day/month/year.

Examples

Split:

var d = document.querySelector('input#data').value;
var [ano, mes, dia] = d.split('-');

Using split again, but this view converting the string for number:

var d = document.querySelector('input#data').value;
var [ano, mes, dia] = d.split('-').map(Number);

Using Date:

var d = document.querySelector('input#data').valueAsDate;
var dia = d.getUTCDate();
var mes = d.getUTCMonth() + 1; // meses iniciam com o valor 0 ¯\_(ツ)_/¯
var ano = d.getUTCFullYear();

Browser other questions tagged

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