Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when add two years to following date will give me incorrect result

var x= new Date("2020/01/01");

x.setDate(x.getDate()+730) // add two years

var p =  new Date(x)

// this print Fri Dec 31 2021 00:00:00 GMT+0300 (Arabian Standard Time)
// which is wrong date 



any help?

What I have tried:

i tried setFullYear() but gives me wrong duration
Posted
Updated 9-Nov-21 20:25pm
Comments
Peter_in_2780 6-Nov-21 20:20pm    
730 days is not two years when a leap-day (Feb 29) is involved.
The Date class in js include lots of methods that will do what you are trying (which is not at all clear from your question).
https://www.w3schools.com/js/js_dates.asp

x.setFullYear(x.getFullYear() + 2);

works for me
 
Share this answer
 
2020 is a leap year, it has 366 days
 
Share this answer
 
Comments
Richard Deeming 10-Nov-21 5:19am    
As Peter already said.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900