Display default date field BR aaaammdd for dd / mm / yyyy with javascript

2

Hello I have a field that automatically gets a date from another system, but it sends me in American standard, I would like to display on the screen with the default dd / mm / yyyy;

 <div class="form-group col-md-2">
            <label for="proximoVenc">Data Ultimo Vencimento</label>
            <input type="text" class="form-control" name="proximoVenc" id="proximoVenc" value="20181105">
          </div>
    
asked by anonymous 11.05.2018 / 15:10

2 answers

2

You can treat this as a string, or convert it to Date and show it with country rules.

Treating as string:

var formatoBr = '2020/05/10'.split('/').reverse().join('/');
console.log(formatoBr); // 10/05/2020

To convert and treat as Date you can do this:

var [ano, mes, dia] = '2020/05/10'.split('/').map(Number);
var date = new Date(ano, mes - 1, dia);
var formatoBr = date.toLocaleDateString('pt-BR');
console.log(formatoBr); // 10/05/2020

// ou ainda:
console.log(date.toLocaleDateString('pt-BR', {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric'
})); // domingo, 10 de maio de 2020

If you always have 8 digits without tabs as you indicated in the question now you can do different ways in N ... a suggestion could be:

var formatoUS = '20200510';
var [ano, mes, dia] = formatoUS.match(/(\d{4})(\d{2})(\d{2})/).slice(1);
var formatoBr = [dia, mes, ano].join('/');
console.log(formatoBr); // 10/05/2020

You can also use type="date" in input , but in this case there are more limitations to formatting, as you give the browser the training task.

    
11.05.2018 / 15:19
1

Using pure JavaScript, you can use Sérgio's answer , but using substring instead of split :

var str = '20181105';
var ano = Number(str.substring(0, 4));
var mes = Number(str.substring(4, 6));
var dia = Number(str.substring(6));
var output = new Date(ano, mes - 1, dia).toLocaleDateString('pt-BR');
console.log(output);

Moment.js

But if you can use an external library, I recommend Moment.js . With it, it's much easier:

var output = moment('20181105', 'YYYYMMDD').format('DD/MM/YYYY');
console.log(output);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Thefirstpart(moment('20181105','YYYYMMDD'))parsethedate(YYYYMMDDindicatesthatitisyear,monthandday),andthenformatgeneratesastringaccordingtotheformatpassed(DD/MM/YYYY->"day / month / year"). See the documentation for more details.

    
11.05.2018 / 16:05