我正在尝试显示“2012年10月9日”的文字。相反,它没有运行该功能,并且显示了许多不受欢迎的日期文本。有谁知道我做错了什么?
你可以玩我的jsfiddle ... http://jsfiddle.net/UP3fd/
这是代码......
var myDate = new Date();
convertDate(myDate);
myDate.setFullYear(2012, 9, 9);
document.write(myDate);
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}
答案 0 :(得分:4)
您在设置日期之前正在调用您的函数,并且您没有在任何地方保存/输出返回值。
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
document.write( convertDate(myDate) );
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}
答案 1 :(得分:1)
var strDate = addZero(d.getDate()) + "/" + addZero((d.getMonth() + 1))+
"/" +d.getFullYear();
alert("strDate :"+strDate)
return strDate;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
答案 2 :(得分:0)
这是正确的代码:
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
myDate = convertDate(myDate);
document.write(myDate);
[...]
答案 3 :(得分:0)
这是经过纠正的代码,这应该会让您重新获得预期的代码。
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
var newDate = convertDate(myDate);
document.write(newDate);
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}