format javascript date and add 365 days - Stack Overflow

I want to add 365 days to a formatted javascript date.var today = new Date();var day = today.getDate()

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 method String.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
Add a ment  | 

2 Answers 2

Reset to default 3

With 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745052982a4608497.html

相关推荐

  • format javascript date and add 365 days - Stack Overflow

    I want to add 365 days to a formatted javascript date.var today = new Date();var day = today.getDate()

    21小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信