How to know if a date is over two months in JS [duplicated]

3

Good, I have two dates in string type, such as the following:

var fecha1 = '2018-11-03';
var fecha2 = '2018-02-03';

And I want to know which is the most efficient code to compare those two dates and know if the difference of months is 2 or higher.

Edit: I have a form with bootstrap and if you tell me the validation code better than better, for now I only have the following in that validation:

fecha: {
                validators:{
                    notEmpty: {
                        message: 'Seleccione una fecha valida'
                    }
                }
            },
    
asked by Ivheror 18.12.2018 в 11:31
source

2 answers

4

To compare 2 dates, you only have to convert these to type Date for it I'll give you an example:

/**
 * Compara 2 numeros indicando si el primero es menor o igual que el segundo
 */
const lte = (n1, n2) => {
  return n1 <= n2;
}

/**
 * Niega un objeto
 */
const not = (o1) => !o1;

/**
 * Obtiene la diferencia en meses de 2 fechas
 */
const diffBetweenMonths = (dateFrom, dateTo) => {
  if(not(dateFrom instanceof Date)) dateFrom = new Date(dateFrom);
  if(not(dateTo instanceof Date)) dateTo = new Date(dateTo);
  
  let months = 0;
  
  months = (dateFrom.getFullYear() - dateTo.getFullYear()) * 12;
  months -= dateTo.getMonth() + 1;
  months += dateFrom.getMonth();
  
  return months <= 0 ? 0 : months;
};

var fecha1 = '2018-11-03';
var fecha2 = '2017-11-03';

if(not(lte(diffBetweenMonths(fecha1, fecha2), 2))) { 
  console.log('Fecha superior a 2 meses');
}

var fecha1 = '2018-04-03';
var fecha2 = '2018-02-03';

if(lte(diffBetweenMonths(fecha1, fecha2), 2)) { 
  console.log('Fecha no superior a 2 meses');
}

The function diffBetweenMonths casts the parameters to Date if they are of another type and then uses the function getMonth() , which returns the month minus 1 (instead of 11 returns 10) obtaining the value of the months and being able to subtract the month from (assumed to be greater) against the month from (which is supposed to be less).

    
answered by 18.12.2018 / 12:21
source
6

What if we subtract the two months to date 1 and compare it to date 2 ?? see the example without using external libraries only using Date

var fecha1 = '2018-04-03';
var fecha2 = '2018-02-03';

const fecha_compare_1 = new Date(fecha1)
const fecha_compare_2 = new Date(fecha2)

fecha_compare_1.setMonth(fecha_compare_1.getMonth()- 2);

console.log('fecha1 es mayor a dos meses? > ${fecha_compare_1> fecha_compare_2} '  )
  

The only thing you have to be careful about is that the date starts from   zero (0), that is, January is the month zero

    
answered by 18.12.2018 в 15:28