Using pure Javascript, you can use the response of Sergio, 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);
Notice that I had to subtract 1 of the month, because the months are indexed at zero (January is zero, February is 1, etc).
Another detail is that toLocaleDateString
may not give the exact "dd/mm/yyyy" format, depending on the locale used and the environment settings, as explained in final part of this reply.
Moment js.
But if you can use an external library, I recommend the Moment js.. With her, 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>
The first part (moment('20181105', 'YYYYMMDD')
) does the Parsing date (YYYYMMDD
indicates that it is year, month and day), and then the format
generates a string according to the format passed (DD/MM/YYYY
-> "day/month/year"). View documentation for more details.
Can you explain better "automatically receives a date from another system"?
– Sergio
That link has what you need
– bio