I want to add 365 days to a formatted javascript date.
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
today = year +"-"+ day +"-"+ month;
var duedate = new Date(today);
duedate.setDate(today.getDate() + 365);
Console says that today.getDate() in the last line is not a function. How do I correctly add 365 days to the formatted date? Thank you!
I want to add 365 days to a formatted javascript date.
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
today = year +"-"+ day +"-"+ month;
var duedate = new Date(today);
duedate.setDate(today.getDate() + 365);
Console says that today.getDate() in the last line is not a function. How do I correctly add 365 days to the formatted date? Thank you!
Share asked Jun 22, 2015 at 2:08 propernounpropernoun 611 gold badge3 silver badges8 bronze badges 3-
today
is a string, so the error is right, there is no methodString.prototype.getDate
(see line:today = year +"-"+ day +"-"+ month;
). – Josh Beam Commented Jun 22, 2015 at 2:09 -
Do not use the Date constructor to parse strings, it's unreliable even if it does "work" in some browsers some of the time. The format you are providing (y-d-m) will most likely be interpreted as y-m-d or invalid. To copy a date, use:
var dateCopy = new Date(+date);
where date is a date object. – RobG Commented Jun 22, 2015 at 3:03 - What format is the input string? Parsing date strings is pretty simple, so is formatting them but you need to show what the format is. – RobG Commented Jun 22, 2015 at 3:07
2 Answers
Reset to default 3With a Date object you can do that.
var now = new Date();
var duedate = new Date(now);
duedate.setDate(now.getDate() + 365);
console.log("Now: ", now);
console.log("Due Date:", duedate);
Is it necessary to edit formatted date? In that case you would need to operate with strings/substrings. Not very beautiful approach.
All you have to do is to remove
today = year +"-"+ day +"-"+ month;
This line converts the date object into string.