javascripte 日期函数笔试题
用javascript编写一个日期格式化函数dateFormat(d,f),输入Date
类型数据和字符串表示日期格式,返回格式化后的字符串。如:
2007-08-01,执行dateFormat(new Date(),"y-m")返回"2007-08",
执行dateFormat(new Date(),"y-m-d")返回"2007-08-01",月份不足10
要在前面补零
[解决办法]
function formatDate(date,pattern){
var s = pattern.split('-');
var result='';
for(var tmp in s){
switch(s[tmp]){
case 'y':
result += date.getFullYear() + '-';
break;
case 'm':
var month = date.getMonth()+1;
result += (month<10? '0'+month : month)+ '-';
break;
case 'd':
var day = date.getDate()+1;
result += (day<10? '0'+day : day);
result += date.getDate();
break;
}
}
if(result.lastIndexOf('-')==result.length-1){
retsult = result.substr(0,result.length-1);
}
return retsult;
}