Error in formatting date function

1

I have this function:

function formatarData(data) {
      var d = new Date(data),
        mes = '' + (d.getMonth() + 1),
        dia = '' + d.getDate(),
        ano = d.getFullYear();

      if (mes.length < 2) mes = '0' + mes;
      if (dia.length < 2) dia = '0' + dia;

      return [ano, mes, dia].join('');
    }

I can play with it and format the date however I want, but when I enter date 01 and 01, it subtracts 1 year, 1 day and 1 month:

example: step by date 01/01/2018 and returns 20171231.

Would anyone know to tell me what's wrong and how to concert it?

    
asked by anonymous 22.03.2018 / 01:51

1 answer

2

This is because input data is sending the value in the format:

2018-01-01 // aaaa-MM-dd

It seems like new Date() is treating the hyphen as a minus sign. Replace the hyphen with another character (it can be a comma or a slash):

2018-01-01 => 2018/01/01 ou 2018,01,01

Just make a replace :

function formatarData(data) {
   data = data.replace(/-/g,"/"); // troca o '-' por '/'

   var d = new Date(data),
     mes = '' + (d.getMonth() + 1),
     dia = '' + d.getDate(),
     ano = d.getFullYear();

   if (mes.length < 2) mes = '0' + mes;
   if (dia.length < 2) dia = '0' + dia;

   return [ano, mes, dia].join('');
}

$("input").trigger("focus");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="date" value="2018-01-01" onfocus="console.log(formatarData(this.value))">
    
22.03.2018 / 02:51