简体   繁体   中英

format javascript date and add 365 days

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM