var today =new Date();
var currentDate = today.getYear() + "-";
if((today.getMonth() + 1) < 10){//getMonth() return 0-11
currentDate += ("0" + (today.getMonth() + 1));//注意月份要加一
}else{
currentDate += (today.getMonth() + 1);
}
currentDate += "-";
if(today.getDate() < 10){//getDate() return 1-31
currentDate += ("0" + today.getDate());
}else{
currentDate += today.getDate();
}
return currentDate;
备注:设置月份时要注意减一
例:
我们为日期对象设置了一个特定的日期 (2008 年 8 月 9 日):
var myDate=new Date()
myDate.setFullYear(2008,7,9)
表示月份的参数介于 0 到 11 之间。也就是说,如果希望把月设置为 8 月,则参数应该是 7。
本文介绍了一种使用JavaScript进行日期格式化的具体实现方法。通过检查月份和日期是否小于10来添加前导零,并展示了如何正确设置月份参数的例子。

被折叠的 条评论
为什么被折叠?



