编写一个函数,将格式为M/D/YYYY的用户输入日期转换为API所需的格式(YYYYMMDD).参数" userDate"和返回值是字符串.
例如,它应将用户输入的日期"12/31/2014"转换为适用于API的"20141231".
function formatDate(userDate)
{
userDate = new Date();
y = userDate.getFullYear();
m = userDate.getMonth();
d = userDate.getDate();
return y + m + d;
}
Run Code Online (Sandbox Code Playgroud)
我的代码有什么问题吗?
无法通过在线测试.
代码有五个问题.
Date()).getMonth方法返回月份索引,而不是月份编号,因此您必须为其添加一个.忽略日期格式问题,可以使用以下方法修复其他问题:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以重新排列字符串中的字符,而不是将字符串解析为日期,并将其格式化为字符串.这规避了日期格式问题:
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];
}
Run Code Online (Sandbox Code Playgroud)