Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

511
Visualizações
How to get previous day's records in MongodDB?

I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day. So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query. So something like this

createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},

But like I explained this is not what I want.

over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

You can get the UNIX timestamps for start and end of previous day this way.
NOTE - start and end in UTC time

var start = new Date().setUTCHours(0,0,0,0)-1000 * 60 * 60 * 24;
var end = new Date().setUTCHours(23,59,59,999)-1000 * 60 * 60 * 24;
console.log(start)
console.log(end)


console.log(new Date(start).toUTCString())
console.log(new Date(end).toUTCString())

over 4 years ago · Santiago Trujillo Relatório

0

var date = new Date();
date ; //# => today date
        
var yesterdayDate =  date.setDate(date.getDate() - 1);
        
createdTime: {
    $lt: date,
    $gt: yesterdayDate,
}
over 4 years ago · Santiago Trujillo Relatório

0

We would assume "the previous day" is a 24 hour period starting at the beginning of the day before today. The easiest way to do this is use time based on UTC and add a timezone offset (if needed).

const timeZoneOffset = -5;

createdTime: {
     $gt: new Date().setUTCHours(0,0,0)-1000 * 60 * 60 * (24 + timeZoneOffset),
     $lt: new Date().setUTCHours(23,59,59,999)-1000 * 60 * 60 * (24 + timeZoneOffset)

},
over 4 years ago · Santiago Trujillo Relatório

0

Whenever you have to work with date/time arithmetic then I recommend moment.js library:

createdTime: {
   $lt: moment().endOf('day').subtract(1, 'day').toDate(),
   $gte: moment().startOf('day').subtract(1, 'day').toDate()
},

Alternative libraries are luxon and day.js

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda