Error in date format function

Asked

Viewed 39 times

1

have that 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('');
    }

and in it I can play and format the date the way I want, but when I put date 01 and month 01, it subtracts 1 year, 1 day and 1 month:

example: step to date 01/01/2018 and return 20171231.

Someone would know to tell me what’s wrong and how to concert it?

  • How are you passing the date to function?

  • As we passed formatarData('01/01/2018') is returning normal: 20180101

  • @dvd passing input type date, the data goes as "2018-01-01"

1 answer

2


That’s because the input data is sending the value in format:

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

It seems to me that new Date() is treating the hyphen as a subtraction sign. Replace the hyphen with another character (it may be a comma or a slash):

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

All you have to do is 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>
<input type="date" value="2018-01-01" onfocus="console.log(formatarData(this.value))">

Browser other questions tagged

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