我设计了一段代码,显示的结束日期基于用户选择的选择日期。我在JavaScript中使用新的Date()函数尝试了它,它运行得很好。但是,当我尝试使用var ProperDate
时,用户选择的日期(我已将其转换为与Javascript中相同的格式),日期不会显示。
守则在这里:
<script>
$('#dSuggest').on("input", function() {
var dInput = this.value;
var Month = dInput.substring(5, 7);
var Date = dInput.substring(8, 10);
var Year = dInput.substring(0, 4);
var ProperDate = Month+"/"+Date+"/"+Year;
console.log(dInput);
$('#output').text(ProperDate);
//var someDate = new Date(ProperDate);
var StartDate = new Date();
var StartDate = StartDate.toLocaleDateString();
if(StartDate > '1/31/2016' ){
var numberOfDaysToAdd = 365;
ProperDate.setDate(ProperDate.getDate() + numberOfDaysToAdd);
//var someDate = ProperDate.toLocaleDateString();
} else {
var n = someDate.getDate();
var numberOfDaysToAdd = n;
ProperDate.setDate(ProperDate.getDate() - numberOfDaysToAdd);
//var someDate = someDate.toLocaleDateString();
}
document.getElementById("demo").innerHTML = someDate;
});
</script>
答案 0 :(得分:1)
基本上你在做
var ProperDate = Month+"/"+Date+"/"+Year;
ProperDate.setDate(ProperDate.getDate() + numberOfDaysToAdd);
但是ProperDate
不是日期对象,它是一个字符串,如果你想使用日期方法,你应该创建一个日期对象而不是字符串
$('#dSuggest').on("input", function() {
var dInput = this.value;
var Month = dInput.substring(5, 7);
var Date = dInput.substring(8, 10);
var Year = dInput.substring(0, 4);
var ProperDate = new Date(Year, Month-1, Date);
var endDate = new Date(2016, 0, 31);
$('#output').text(Month + "/" + Date + "/" + Year;);
var StartDate = new Date();
if (StartDate > endDate) {
var numberOfDaysToAdd = 365;
} else {
var numberOfDaysToAdd = n;
}
ProperDate.setDate(ProperDate.getDate() + numberOfDaysToAdd);
document.getElementById("demo").innerHTML = properDate;
});