How can I get the minimum and maximum date of a javascript fix?

0

I have this arrangement:

var arr = ["2018-06-07","2018-06-30","2018-06-01","2018-06-21","2018-07-20"];

And I need to get the maximum and minimum date with javascript, I have tried with this function:

var min = new Date(Math.max.apply(null,arr));
var max = new Date(Math.min.apply(null,arr));

But they give me back a "NaN" value.

What will I be doing wrong? or is there another way to get the major and minor date of an arrangement ?, Thanks

    
asked by Fernando Garcia 20.06.2018 в 21:37
source

3 answers

1

The detail is that you are looking for the minimum and maximum value of a string, you must change your arrangement to Date () and you will not have problems

const arr = ["2018-06-07","2018-06-30","2018-06-01","2018-06-21","2018-07-20"];

let arrayFechas = arr.map((fechaActual) => new Date(fechaActual) );

var max = new Date(Math.max.apply(null,arrayFechas));
var min = new Date(Math.min.apply(null,arrayFechas));

console.log("valor minimo" , min) 
console.log("valor maximo" ,max)

Another option but you still convert the array into Date, traversing it and returning an element is with Array.reduce

const arr = ["2018-06-07","2018-06-30","2018-06-01","2018-06-21","2018-07-20"];

var min = arr.reduce(function (valor1, valor2) { return new Date(valor1) <  new Date(valor2) ? valor1 : valor2; }); 
var max = arr.reduce(function (valor1, valor2) { return new Date(valor1) > new Date(valor2) ? valor1 : valor2; });

console.log("valor minimo" , min) 
console.log("valor maximo" ,max)
    
answered by 20.06.2018 / 21:57
source
2

Using the class Date of JavaScript you can do it easily because it allows you to do comparison operations with the dates and make dates from strings. Then it's just a matter of iterating the arrangement and saving the major or minor.

var arr = ["2018-06-07","2018-06-30","2018-06-01","2018-06-21","2018-07-20"];

var mayorDate= new Date(arr[0]);
var menorDate= new Date(arr[0]);

for (var i = 0; i<arr.length; i++){
	var arrDate= new Date(arr[i]);
	if(arrDate > mayorDate){
  	mayorDate=arrDate
  }
  if(arrDate < menorDate){
  	menorDate=arrDate
  }
}

console.log("Fecha mayor: "+mayorDate.toUTCString());
console.log("Fecha menor: "+menorDate.toUTCString());
    
answered by 20.06.2018 в 21:53
1

You should do the following:

    var dates = [];
    dates.push(new Date("2011/06/25"))
    dates.push(new Date("2011/06/26"))
    dates.push(new Date("2011/06/27"))
    dates.push(new Date("2011/06/28"))
    var max = new Date(Math.max(...dates));
    var min = new Date(Math.min(...dates));
    console.log(max);
    console.log(min);

Try this from your browser console, you should work then adapt it to your needs, in this case you put the corresponding dates.

    
answered by 20.06.2018 в 21:57