2

I have this array:

DatosFechas = ["2020-04-29", "2020-04-19", "2020-04-07", "2020-04-30", "2020-04-30", "2018-01-22"]

And I would like to get the oldest or the newest date from a given range.

Ths function that trying to get work:

function ObtenerMaxMinRangoFechas(DatosFechas) {
    let moments = DatosFechas.map(x => moment(x)),
    maxDate = moment.max(moments)
    return maxDate

}

Thx

My date array is longer, just for the purpose of this posting it´s reduced.

This is the error:

enter image description here

Is not giving me the maxdate.

Kentron.dna
  • 183
  • 11

5 Answers5

3

The returned maxDate variable is actually a Moment object. You can simply format it to get the desired result like:

const DatosFechas = ["2020-04-29", "2020-04-19", "2020-04-07", "2020-04-30", "2020-04-30", "2018-01-22"]
function ObtenerMaxMinRangoFechas(DatosFechas) {
    let moments = DatosFechas.map(x => moment(x)),
    maxDate = moment.max(moments)
    return maxDate.format('YYYY-MM-DD')
}

console.log( ObtenerMaxMinRangoFechas(DatosFechas) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.1/moment.min.js"></script>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

Sort the dates array and grab the last one.

DatosFechas = ["2020-04-29", "2020-04-19", "2020-04-07", "2020-04-30", "2020-04-30", "2018-01-22"]
const sortedDates = DatosFechas.sort((a, b) => moment(a) - moment(b));
console.log('NEWEST Date',sortedDates[sortedDates.length-1])
console.log('OLDEST Date',sortedDates[0])

Note: You don't really need moment for your case. You can use js inbuilt Date feature. See here


gdh
  • 13,114
  • 2
  • 16
  • 28
1

You are doing great, you have done right. Just problem is that you have to formant your return moment object instead of returning it as an object.

Use it-

function ObtenerMaxMinRangoFechas(DatosFechas) {
    const moments = DatosFechas.map(x => moment(x));
    const maxDate = moment.max(moments);
    return maxDate.format('YYYY-MM-DD');
}
Anurag Yadav
  • 294
  • 1
  • 9
1

In what format do you want to return the first and last date? Here is an example with an array of the first and last string:

let dates = ["2020-04-29", "2020-04-19", "2020-04-07", "2020-04-30", "2020-04-30", "2018-01-22"]

const getFirstAndLastDate = (dates) => {
  dates = dates.sort()
  return [dates[0], dates[dates.length - 1]]
}

console.log(getFirstAndLastDate(dates))
Thomas
  • 39
  • 1
  • 5
1

Moment.max seems to be returning an moment object rather than a string in the format you want. to get the string format, you'll need to call format and pass the format you want, like this

moment.format('YYYY-MM-DD')  

let's put this together,

function ObtenerMaxMinRangoFechas(DatosFechas) {
    let moments = DatosFechas.map(x => moment(x)),
    maxDate = moment.max(moments).format('YYYY-MM-DD');
    return maxDate
}
user3366943
  • 253
  • 1
  • 6