Natively, the Date
Javascript does not give many options to convert strings to a date (actually, few formats are in fact "official" and many others work differently depending on the browser).
The way is to manipulate the string manually. One way to do it is to:
let sdata = '201909091504';
let [ano, mes, dia, hora, minuto] = sdata.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/).slice(1, 6);
let dataFormatada = `${ano}-${mes}-${dia} ${hora}:${minuto}`;
console.log(dataFormatada); // 2019-09-09 15:04
The regular expression used in the method match
uses the shortcut \d
(which corresponds to digits from 0 to 9) and uses quantifiers {n}
to pick up exactly n
digits. I also use parentheses, which form capture groups, so each stretch in question is returned separately.
Then I use the method slice
to take the stretch of the array that interests me (since match
returns an array with various other information), attribute to the respective variables (using the syntax of destructuring assingment) and I grant everything.
One detail is that the above code does not check whether the date is valid (if the day is longer than 31, etc). If you want to do this, one way is:
function pad(valor) {
return valor.toString().padStart(2, '0');
}
let sdata = '201909091504';
let [ano, mes, dia, hora, minuto] = sdata.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/).slice(1, 6).map(s => parseInt(s));
let d = new Date(ano, mes - 1, dia, hora, minuto);
if (d.getFullYear() === ano && d.getMonth() + 1 === mes && d.getDate() === dia
&& d.getHours() === hora && d.getMinutes() === minuto) {
let dataFormatada = `${ano}-${pad(mes)}-${pad(dia)} ${pad(hora)}:${pad(minuto)}`;
console.log(dataFormatada); // 2019-09-09 15:04
} else {
console.log('data inválida');
}
I create a Date
using the values obtained by regex (converting them to numbers with parseInt
). Then I check if the values of the Date
are the same as the original variables. I did this because the Date
accepts values as day 32 and makes some adjustments (January 32 is adjusted to February 1, for example). So if any of the values is different, it is because the original date contains invalid values.
Also note that I subtracted 1 from the month because in Date
javascript months are indexed to zero (January is zero, February is 1, etc).
Another alternative is to use the Moment js.:
let sdata = '201909091504';
let data = moment(sdata, 'YYYYMMDDHHmm'); // lê o formato acima e cria a data
// mostra a data em outro formato
console.log(data.format('YYYY-MM-DD HH:mm')); // 2019-09-09 15:04
<script src="https://momentjs.com/downloads/moment.min.js"></script>
One advantage of Moment.js is that it also validates the date. Just use isValid()
, as shown in reply of the Virgilio.
The format will always be the same, year-month-day hour:minutes?
– LeAndrade
sdata.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/)
then just concatenate– Valdeir Psr