Reputation: 13
I have a date let us say "17-2-1978" and i checked if it is in the past. While checking, if it is in the past, i want to change only the year to 2018. How can this be done?
code below:
function startCountDown(){
var testing = document.getElementById("events-div").lastChild.textContent;
alert(testing);
var selectedDate = new Date(testing);
var now = new Date();
if (selectedDate < now) {
var d = new Date();
var n = d.getFullYear()+1;
selectedDate.setDate(selectedDate + n);
alert(selectedDate);
}
}
Upvotes: 1
Views: 540
Reputation: 2096
You can use the setFullYear
method. Example:
var d = new Date();
d.setFullYear(2018);
To display it in the format you want you can use getDate
, getMonth
and getYear
var formatted = [d.getDate(), d.getMonth() + 1, d.getYear()].join('-');
The month is zero-based, so you'll need to add 1 to it.
Upvotes: 2
Reputation: 735
First the date string needs to be correctly parsed to construct the date object:
var from = testing.split("-");
var d = new Date(from[2], from[1] - 1, from[0]);
var today = new Date();
if (d < today) {
d.setFullYear(2018);
} else {
//date is in future so no change
}
See example below:
var testing="17-2-1978";
var from = testing.split("-");
var d = new Date(from[2], from[1] - 1, from[0]);
var today = new Date();
if (d < today) {
d.setFullYear(2018);
} else {
//date is in future so no change
}
document.getElementById("date").innerHTML=d;
<p id="date"></p>
Upvotes: 1