There are five problems with the code.
- It ignores the input parameter and uses the current time instead (
Date()
).
- It assumes that the computer where it runs uses the m/d/y date format to parse the string (if it actually would have parsed the string).
- The
getMonth
method returns the month index, not the month number, so you have to add one to it.
- It uses addition to put the values together instead of string concatenation.
- It doesn't format the month and date into two digits.
Ignoring the date format issue, the others can be fixed using:
function formatDate(userDate) {
userDate = new Date(userDate);
y = userDate.getFullYear().toString();
m = (userDate.getMonth() + 1).toString();
d = userDate.getDate().toString();
if (m.length == 1) m = '0' + m;
if (d.length == 1) d = '0' + d;
return y + m + d;
}
Instead of parsing the string to a date, and the format it to a string again, you can just rearrange the characters in the string. This circumvents the date format issue:
function formatDate(userDate) {
var parts = userDate.split('/');
if (parts[0].length == 1) parts[0] = '0' + parts[0];
if (parts[1].length == 1) parts[1] = '0' + parts[1];
return parts[2] + parts[0] + parts[1];
}