Convert Date to date field

1

I have a field that receives a date value as in the example: 24/10/18 .

I need to replicate this field to one of date type but following the value rule that date requires. Example: 2018-09-24 .

That is, convert date 24/10/18 to 2018-10-24 .

<label>Data um</label>
<input type="text" class="form-control" id="dataum" name="dataum" value="24/09/18">
<br>
Converte a data 24/09/18 para 2018-09-24 para adicionar o resultado num value do tipo date
<br>
<label>Data Copia</label>
<input type="date" class="form-control" id="dataumcopia" name="dataumcopia" value="2018-09-24">
    
asked by anonymous 24.09.2018 / 17:38

3 answers

3

Simple like this:

var data = '24/10/2018';
var date = data.split('/').reverse().join('-');
console.log(date);

Edit.:

I have now realized that the date comes with only 2 digits of the year, and you need the 4 digit return. In that case, it's a little different. If the date is not to be before the 2000s, you can do so:

var data = '24/10/18';
var date = data.split('/').reverse()
date[0] = '20' + date[0];
date = date.join('-');
console.log(date);
    
24.09.2018 / 17:54
2

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="">
    
24.09.2018 / 19:43
1

If you do not go beyond the year 2000 (it's too long, rs), you can do this:

let str =  document.getElementById('dataum').value; //pega o valor
let split = str.split('/').reverse(); // quebra o valor entre os caracteres '/' e transforma o array na forma reversa
let shift = split.shift(); // remove o primeiro elemento e guarda na variavel
let join = split.join('-'); // junta os elementos do array separando-os por '-' 
let string = '20' + shift + '-' + join; //gera a string final

console.log(string);

document.getElementById('dataumcopia').value = string;
<label>Data um</label>
<input type="text" class="form-control" id="dataum" name="dataum" value="24/09/18">
<br>
Converte a data 24/09/18 para 2018-09-24 para adicionar o resultado num value do tipo date
<br>
<label>Data Copia</label>
<input type="date" class="form-control" id="dataumcopia" name="dataumcopia" value="">

I left the code all commented, if in doubt, just ask.

    
24.09.2018 / 18:18