Filter dates in array

4

Currently I use firebase as my database. I need to pick up a collection and bring the data for a specific month according to two fields in my collection. The firebase does not let us make querys with different fields so I have chosen to bring everything from the year 2018 and filter in my array the specific month.

I make the following query in firebase:

  let start = new Date('2018-01-01');
  let end = new Date('2018-12-31');
  let ref = db.collection('eventos').where("dt_inicio", ">", start).where("dt_inicio", "<", end).orderBy("dt_inicio", "asc");


  ref.get()
  .then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
     console.log(doc.data());
    });
  });

It returns me to doc.data (), and giving a console.log I have the following return.

I'd like to filter the start date and end date by the month of 08/2018.

How do I proceed?

    
asked by anonymous 18.10.2018 / 01:58

1 answer

0

Using pure JS, you can use a combination of filter and some methods of the Date object. I understood that you want to filter the results by month and year, so it would look like this:

// Recebe o array com os resultados, o mês e o ano no padrão JS. Volta um array filtrado
function filtrarResultados(array, mes, ano) {
    return array.filter(resultado => {
        // Salva o mês e ano de cada campo para poder verificar
        const dt_inicioMes = resultado.dt_inicio.getMonth()
        const dt_inicioAno = resultado.dt_inicio.getFullYear()
        const dt_fimMes = resultado.dt_fim.getMonth()
        const dt_fimAno = resultado.dt_fim.getFullYear()
        return dt_inicioMes == mes && dt_fimMes == mes && dt_inicioAno == ano && dt_fimAno == ano
    })
}

This code snippet will filter and return an array only with results that have dt_inicio and dt_fim in a given month and a given year.

    
18.10.2018 / 02:23