I Am trying to form a date which is 3 months before the current date. I get the current month by the below code
var currentDate = new Date(); var currentMonth = currentDate.getMonth()+1;
Can you guys provide me the logic to calculate and form a date (an object of the Date
data type) considering that when the month is January (1), 3 months before date would be OCtober (10)?
Advertisement
Answer
var d = new Date(); d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
var d = new Date("January 14, 2012"); console.log(d.toLocaleDateString()); d.setMonth(d.getMonth() - 3); console.log(d.toLocaleDateString());
There are some caveats…
A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn’t August or Decemeber), that day of the month doesn’t exist in the previous month.
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
It also says that one month is 30.4167 days long:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by “one month before”. Go have a conversation with your product owner.
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
const d = new Date("March 31, 2019"); console.log(d.toLocaleDateString()); const month = d.getMonth(); d.setMonth(d.getMonth() - 1); while (d.getMonth() === month) { d.setDate(d.getDate() - 1); } console.log(d.toLocaleDateString());
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don’t have to install a library! You don’t have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!