Do split
and reverse
, as the other answers suggest, it works well if the date typed is valid.
But as the date is being typed in a field input type="text"
, means that any value can be entered into it. That is, the field can have since invalid dates (such as 31/02/18
or 10/99/18
) until some text that does not even remotely remember a date (abc
).
So I recommend that you also validate the date being typed, before setting it on input type="date"
.
See the difference between setting a valid value and an invalid 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’m testing on Chrome 63, I don’t know if the behavior is the same on all browsers (anyway, I recommend validating the date before setting it to avoid these problems).
That is why it is important to validate the date. For this, you can create a Date
with the values passed. There is only one detail: the constructor of Date
accepts higher than allowable values (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 month zero, February is 1, etc. 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 build a Date
and check if the end 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");
}
The parseInt
will return NaN
if the values obtained are not numbers. That is why the test followed with isNaN
to check if they are indeed numbers.
Note: from ES6 you can use the destructuring assignment (see here the browser compatibility table):
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 on input
. I used the method toISOString()
to return the date in "yyyy-mm-dd" format, and used substring
to take only the date part (since the method toISOString()
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 don’t mind adding an external library to your project, I recommend the Moment js., that makes this job 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>
<input type="date" class="form-control" id="dataumcopia" name="dataumcopia" value="">