我正在尝试使用日期格式打印日期,例如1998年5月9日,但是运行代码时,我得到081/5/1998
我究竟做错了什么?

var c = new Date("September 5, 1998 08:45:00");

function datePrinter(){
var monthPrinter = c.getMonth();
var dayPrinter = c.getDate();
var yearPrinter = c.getFullYear();


if(monthPrinter < 10){
monthPrinter = "0" + monthPrinter;
monthPrinter = monthPrinter + 1;
}
if(datePrinter < 10){
datePrinter = "0" + dayPrinter;
}

document.write(monthPrinter + "/" +dayPrinter + "/" + yearPrinter);


}

datePrinter();

最佳答案

当您在数字前面添加或附加字符串时,结果将成为字符串。当您增加它时,它将进行字符串连接而不添加。您需要再次使用parseInt()将字符串解析为Number。



var c = new Date("September 5, 1998 08:45:00");

function datePrinter(){
var monthPrinter = c.getMonth() + 1;
var dayPrinter = c.getDate();
var yearPrinter = c.getFullYear();

if(monthPrinter < 10){
monthPrinter = "0" + monthPrinter;
}
if(dayPrinter < 10){
dayPrinter = "0" + dayPrinter;
}

document.write(monthPrinter + "/" +dayPrinter + "/" + yearPrinter);


}

datePrinter();

关于javascript - 为什么这段代码运行错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41581986/

10-11 12:45