0

我正在尝试显示文本“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);
}
4

4 回答 4

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);
}
​
于 2012-10-30T14:36:29.503 回答
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;
    }
于 2017-11-23T05:43:38.070 回答
0

这是正确的代码:

var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
myDate = convertDate(myDate);
document.write(myDate);

[...] 
于 2012-10-30T14:37:16.267 回答
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);

}
于 2012-10-30T14:42:00.790 回答