Jonathan Lermitage
Jonathan Lermitage

Reputation: 679

Add a year to a date (and deal with leap year)

Using "Mongodb" shell, I have to compute the date of the day + one year. I can add 365 days do the current date, but I'll be wrong with leap year. Example:

print(new Date(new Date().getTime() + (1000 * 3600 * 24 * 365)));

We are "2015-06-22". This "date + 365 = 2016-06-21" :) I have not found any date function on Mongodb. How do you deal with leap year?

Upvotes: 0

Views: 2904

Answers (1)

Treesrule14
Treesrule14

Reputation: 711

Supposing you just want it to be the same date for the next year you can use

var a = Date()
a.setFullYear(a.getFullYear() + 1)

As Sylvain Leroux points out you will have to handle the edge case of the 29th of February by default it will change to the first of March when you add a year. This will not happen if you add a year to march 1st of the year before a leap year.

Upvotes: 3

Related Questions