0

What I am looking for:

If current date is 1st january 2020, then i want 31st dec, 2020.

If its 1st feb 2020 then i want 31st jan, 2021.

Is there any way to get the above result without third party library?

What I tried was to add 365 days but as we know the days are not 365 always so it did not work.

Looking for solution

MhkAsif
  • 537
  • 3
  • 18
  • 1
    See how to add a year here https://stackoverflow.com/questions/33070428/add-year-to-todays-date – Vishal Dhawan Jul 19 '20 at 14:55
  • Add one year, subtract one day, job done. – Niet the Dark Absol Jul 19 '20 at 14:59
  • 2
    It's not clear what you're asking. If you want to add a year (not 365 days) because sometimes years are more than 365 days, add a year as shown in [the answers to this question](https://stackoverflow.com/questions/33070428/add-year-to-todays-date). But *"If current date is 1st january 2020, then i want 31st dec, 2020."* isn't adding a year, it's adding a year-minus-one-day. If you want to do that, do exactly that: Add a year (`dt.setFullyear(dt.getFullYear() + 1)`) and subtract a day (`dt.setDate(dt.getDate() - 1)`). – T.J. Crowder Jul 19 '20 at 14:59
  • 1
    thanks, @T.J.Crowder. it worked – MhkAsif Jul 19 '20 at 15:12
  • If this is only for the 1st of the month, you can do it in one go: `d.setFullYear(d.getFullYear() + 1, d.getMonth(), 0)`. Setting the date to 0 sets it back to the last day of the previous month, effectively subtracting one day from the 1st. :-) – RobG Jul 20 '20 at 04:47

0 Answers0