Reputation: 26
I have designed a piece of code which displays an end date which is based on the select date which is selected by a user. I tried it using the new Date() function in JavaScript and it worked perfectly. However when I try to use the var ProperDate
which is the Date the user selected (which I have converted as the same format as it would be in Javascript) the date does not display as it should.
The Code Here:
<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>
Upvotes: 0
Views: 133
Reputation: 318342
Basically you're doing
var ProperDate = Month+"/"+Date+"/"+Year;
ProperDate.setDate(ProperDate.getDate() + numberOfDaysToAdd);
but ProperDate
is not a date object, it's a string, you should be creating a date object, not a string, if you want to use date methods
$('#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;
});
Upvotes: 1