Convert Date to date field

Asked

Viewed 232 times

1

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

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

That is, convert the date 24/10/18 for 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">

3 answers

3


Simple as that:

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

Edit.:

I realized now that the date only comes with 2 digits of the year, and you need the return in 4 digits. In this case, it is a little different. If the date isn’t 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);

2

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="">

1

If it does not exceed the year 2000 (much more, rs), da to do so:

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, in case you have any questions, just ask.

Browser other questions tagged

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