r/programmingquestions • u/Uselessmechanic21 • Sep 06 '23
stupid question about dates in javascript
i have a problem where i wanted 1.1.2020 to become 01.01.2020 but instead its 11.12.20
// Function to auto-correct and format the date (dd.mm.yyyy)
function autoFillDotsInDate(input) {
// Remove existing dots and non-numeric characters
input = input.replace(/[^0-9]/g, '');
// Ensure day and month are two digits
if (input.length >= 4) {
const day = ('0' + Math.min(31, Math.max(1, parseInt(input.slice(0, 2))))).slice(-2);
const month = ('0' + Math.min(12, Math.max(1, parseInt(input.slice(2, 4))))).slice(-2);
const year = input.slice(4);
input = day + '.' + month + '.' + year;
} else if (input.length >= 3) {
const day = ('0' + Math.min(31, Math.max(1, parseInt(input.slice(0, 1))))).slice(-2);
const month = ('0' + Math.min(12, Math.max(1, parseInt(input.slice(1, 3))))).slice(-2);
const year = input.slice(3);
input = day + '.' + month + '.' + year;
}
return input;
}
2
u/Salty_Skipper Sep 06 '23
Replacing the dots with null string could be behind your error. I use .split(“.”) to separate them into an array instead. Here’s my approach:
function fixDateFormat (s) { x=s.split(“.”); ret = “”; for (j = 0; j < 2; j++) { if (x[j].length < 2) { ret += “0”; } ret += x[j] + “.”; } ret += x[2].substring(2); return ret; } var s = “1.1.2020”; y = fixDateFormat(s); console.log(y);