Make split
and reverse
, as the other answers suggest, works well if the date entered is valid.
But since the date is being typed in a input type="text"
field, it means that any value can be typed in it. That is, the field can have from invalid dates (such as 31/02/18
or 10/99/18
) to any text that does not even remember a date ( abc
).
So I recommend that you also validate the date being entered, before setting it to input type="date"
.
Here's the difference between setting a valid value and an invalid value in the example below:
function setar(valor) {
document.getElementById('data').value = valor;
}
<input type="date" id="data" value="" />
<br/>
<input type="button" value="setar data inválida" onclick="setar('2018-02-31')" />
<input type="button" value="setar data válida" onclick="setar('2018-02-01')"/>
When setting an invalid date, the field value is "reset". I am testing on Chrome 63, I do not know if the behavior is the same in all browsers (anyway, I recommend you validate the date before setting it to avoid these problems).
So it's important to validate the date. For this, you can create a Date
with the past values. There is only one detail: the Date
constructor accepts values greater than those allowed (month 13, February 31, etc.), making adjustments to the final value. Another detail is that in this constructor the value of the month is indexed to zero: that is, January is zero month, February is 1, and so on. Examples:
// mês 13 é ajustado para fevereiro do ano seguinte
console.log(new Date(2018, 13, 1)); // 2019-02-01
// 31 de fevereiro é ajustado para 3 de março
console.log(new Date(2018, 1, 31)); // 2018-03-03
That said, one way to validate is to construct a Date
and check that the final values are the same (ie, if there was no adjustment):
var v = '24/10/18'.split('/');
var dia = parseInt(v[0]);
var mes = parseInt(v[1]);
var ano = parseInt(v[2]);
// verificar se os valores são números
if (isNaN(dia)) {
// dia inválido
}
if (isNaN(mes)) {
// mês inválido
}
if (isNaN(ano)) {
// ano inválido
}
// corrigir os valores (supondo que o ano 18 seja 2018)
ano += 2000;
mes -= 1; // mês é indexado em zero (janeiro é zero, fevereiro é 1, etc)
var date = new Date(ano, mes, dia);
if (date.getFullYear() == ano && date.getMonth() == mes && date.getDate() == dia) {
console.log("data válida");
}
parseInt
will return NaN
if the values obtained are not numbers. So the test done next with isNaN
to check if they are indeed numbers.
Note: From ES6 you can use destructuring assignment (see here the compatibility table of the browsers):
var [dia, mes, ano] = '24/10/18'.split('/').map(function(v) { return parseInt(v) });
var mes = mes - 1;
var ano = ano + 2000;
Once the date is valid, you can set it to input
. I used the toISOString()
method to return the date in the "yyyy-mm-dd" format, and I used substring
to get only the part of the date (since the toISOString()
method also returns the time):
var v = '24/10/18'.split('/');
var dia = parseInt(v[0]);
var mes = parseInt(v[1]);
var ano = parseInt(v[2]);
// verificar se os valores são números
if (isNaN(dia)) {
// dia inválido
}
if (isNaN(mes)) {
// mês inválido
}
if (isNaN(ano)) {
// ano inválido
}
// corrigir os valores (supondo que o ano 18 seja 2018)
ano += 2000;
mes -= 1; // mês é indexado em zero (janeiro é zero, fevereiro é 1, etc)
var date = new Date(ano, mes, dia);
if (date.getFullYear() == ano && date.getMonth() == mes && date.getDate() == dia) {
document.getElementById('dataumcopia').value = date.toISOString().substring(0, 10);
}
<input type="date" class="form-control" id="dataumcopia" name="dataumcopia" value="">
Momentjs
If you do not mind adding an external library to your project, I recommend Moment.js , which makes this work a lot easier:
var d = moment('24/10/18', 'DD/MM/YY');
if(d.isValid()) {
document.getElementById('dataumcopia').value = d.format('YYYY-MM-DD');
}
<script src="https://momentjs.com/downloads/moment.min.js"></script><inputtype="date" class="form-control" id="dataumcopia" name="dataumcopia" value="">