最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

format javascript date and add 365 days - Stack Overflow

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论