The way you're reformatting the string is fine, even though it seems like a lot of code for a small job, slice is pretty fast. Some alternatives (not necessarily "better", just different):
// Reformat yyyyMMdd:hhmmss as dd.mm.yyyy hh:mm:ss
function formatMatch(s) {
let b = s.match(/\d\d/g) || [];
return `${b[3]}.${b[2]}.${b[0]}${b[1]} ${b[4]}:${b[5]}:${b[6]}`;
}
function formatReplace(s) {
return s.replace(/(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})(\d{2})/, '$3.$2.$1 $4:$5:$6');
}
formatDate = (data) => {
return data.slice(6, 8) + "." + data.slice(4, 6) + "." + data.slice(0, 4) + " " + data.slice(9, 11) + ":" + data.slice(11, 13)
}
let s = '20200323:123445';
console.log(formatDate(s));
console.log(formatMatch(s));
console.log(formatReplace(s));
If you want to get an actual Date object, then instead of using the bits to create another string, just pass them into the constructor:
// Parse yyyyMMdd:hhmmss to Date object
function parseD(s) {
let b = s.match(/\d\d/g) || [];
return new Date(b[0]+b[1], b[2]-1, b[3], b[4], b[5], b[6]);
}
let s = '20200327:134523';
console.log(parseD(s).toString());
The use of || []
means that if there's no match, an empty array is returned so all the b[*]
terms return undefined and the result is an invalid date.
The above uses match, but slice or substring can be used the same way.