我正在创建一个脚本以在某个特定字段中输入日期,它所需的格式是MMM DD,YYYY,因为您可以看到格式在月份名称和日期之间有一个空格,另一个在逗号和年份之间。我搜索了很多地方并尝试了下面的代码,但它返回值 NaN,2018 我的代码列在下面 -
this.getCurrentDate = function () {
var d = new Date();
var currentDate = d.getDate();
var currentMonth = d.getMonth()+1;
var currentYear = d.getFullYear();
if (currentDate < 10){
currentDate = '0'+currentDate;
}
if (currentMonth < 10){
currentMonth = '0'+currentMonth;
}
var today = currentMonth + '\xa0' + currentDate-1 + ',' + '\xa0' + currentYear;
console.log(today);
return today;
};
答案 0 :(得分:0)
你的问题在于这行代码:
var today = currentMonth + '\xa0' + currentDate-1 + ',' + '\xa0' + currentYear;
所以以前你将这两个变量设置为字符串:
if (currentDate < 10){
currentDate = '0'+currentDate;
}
if (currentMonth < 10){
currentMonth = '0'+currentMonth;
}
在today
处的变量currentDate
中,您试图从字符串中减去整数1。因此,NaN(非数字)。
答案 1 :(得分:0)
您正在从导致错误的字符串中减去1。
this.getCurrentDate = function () {
var d = new Date();
var currentDate = d.getDate();
var currentMonth = d.getMonth()+1;
var currentYear = d.getFullYear();
if (currentDate < 10){
currentDate = '0'+currentDate;
}
if (currentMonth < 10){
currentDate--; //Fixed here.
currentMonth = '0'+currentMonth;
} //removed -1 from current date
var today = currentMonth + '\xa0' + currentDate + ',' + '\xa0' + currentYear;
console.log(today);
return today;
};
在将数字更改为字符串之前,必须从数字中减去值。这将立即生效。