-3

I have this dates function:

var isAnnual;
var setupDate="05/09/2016"
var currDate = new Date();//today

I need to check if subtraction of the months in dates above is equal to zero.

Any idea what is the best way to implement it?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 4
    Did you search? [`[javascript] date month difference`](https://stackoverflow.com/search?q=%5Bjavascript%5D+date+month+difference) – Felix Kling Jul 19 '16 at 09:19

2 Answers2

0

Fetch the month from date and subtract it

Note: month starts from 0 i.e. Jan -0 , Dec -11

var s= new Date("05/09/2016");
var currDate = new Date();
console.log(s.getMonth()-currDate.getMonth());
divy3993
  • 5,732
  • 2
  • 28
  • 41
abhirathore2006
  • 3,317
  • 1
  • 25
  • 29
  • 1
    This will work only if both dates are during the same year. This will think that e.g. there's no difference between 5/9/2016 and 5/9/1999. – JJJ Jul 19 '16 at 09:49
  • yes, you are right, in that case you can subtract the year too then convert year to months, – abhirathore2006 Jul 20 '16 at 06:15
0

I think the question is not asked very accurate, because it does not really desribe what you want, e.g. there are at least these options:

1.) You want to compare the current Month with the month of the given date, which is by the way also not accurate formatted. Pseudocode for that:

givenDate := "05/09/2016";
currentDate := determineCurrentDate();

givenMonth := extractMonthFromDateString(givenDate);
currentMonth := extractMonthFromDate(currentDate);

return givenMonth = currentMonth;

2.) You want to determine if the currentDate is inside the month of the given Date Pseudocode for that:

givenDate := "05/09/2016";
currentDate := determineCurrentDate();

givenMonth := extractMonthFromDateString(givenDate);
currentMonth := extractMonthFromDate(currentDate);
givenYear := extractYearFromDateString(givenDate);
currentYear := extractYearFromDate(currentDate);

return givenMonth = currentMonth AND givenYear = currentYear;

A JS based solution for the first approach is the following one, the second option is really easy to build out of this one:

var setupDate = "05/09/2016"; // Format: dd/mm/yyyy
var currDate = new Date();
var monthsEqual = currDate.getMonth() == setupDate.replace(
        /(\d\d)\/(\d\d)\/(\d{4})/, // regex for dd/mm/yyyy
        function(date, day, month, year){ // regard the order of the params
            return new Date(year, parseInt(month)-1, parseInt(day)).getMonth();
        });

console.log(monthsEqual);

nemoinho
  • 604
  • 4
  • 15