1

I want to validate a date field where only last 12 months or 15 months accepted from today’s date as well for future date from today’s date any JavaScript code for this condition

I used this logic

var difference = (date2year*12 +date2month + date2day )-  (date1year*12 +date1month + date1day )

&

var difference = date2month-date1month +12* (dare2year-date1year)

For calculating the difference

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • And what is your question? – Reporter Feb 23 '23 at 09:48
  • Add or subtract the required number of months from today, then see if the test date is greater than or less than as appropriate. See [*JavaScript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date?r=SearchResults&s=1%7C457.1322) – RobG Feb 23 '23 at 11:10

2 Answers2

0

Why don't you just use the built-in Date? You can add/subtract months like this:

const date = new Date(); // Current moment
// Plus 15 months
date.setMonth(date.getMonth() + 15);
// Minus 15 months
date.setMonth(date.getMonth() - 15);

Situations like 2024/15/11 don't occur (it automatically corrects them). 2024/15/11 will turn into 2025/03/11.

Is it what you want, or I didn't catch your issue?

SNBS
  • 671
  • 2
  • 22
-1

In such scenarios, I prefer moment.jsMoment JS, it has many methods to help you play around with date. The in-built Date class in JS is a bit difficult to utilise.

Let's say you want to calculate the difference between today and the given date, say date1, with moment we do:

const a = moment(); // today
const b = moment(date1); // given date, can be epoch, ISO, Date, string, etc 
a.diff(b) // this will be a - b and result will be in milliseconds

There are several other methods like between for your use case, please go through the documentation. Let me know if you face any difficulty.

Ayush S
  • 99
  • 2