Reputation:
I have a code in which I am testing the difference in months between two dates. To get old date I am doing following thing
var oldDate = new Date();
oldDate.setMonth(oldDate.getMonth() - 5);
But monthsOldDate
is returning something else and not five month old date why is this behaving weirdly today? and how shall I fix this?
Upvotes: 1
Views: 703
Reputation: 1636
When trying to add or subtract months from a Javascript Date() Object which is an end date of a month, JS automatically advances your Date object to next month’s first date if the resulting date does not exist in its month.
I would recommend using a library like momentjs for this
You can do this by
var monthsOldDate = moment().subtract(6, 'months');
console.log(monthsOldDate.month()) //will log 10 (November)
monthsOldDate = monthsOldDate.set("month", monthsOldDate.month())
console.log(monthsOldDate.format("Do MMMM YYYY")) //30th November 2017
Upvotes: 1
Reputation: 6877
It's because it's the 31st.
When you call the setMonth()
method with the argument -2
, it sets the date to 31 Nov 2017. That's not an actual date, so it gets converted to 1 Dec 2017.
See the last paragraph of the Description
section for an explanation of this behavior.
Upvotes: 3