0

I need to query in my mongoDB in between yesterday beginning of the day and yesterday end of the day which is

T00:00:00 and T11:59:59

However everytime I add .toDate() method to any of the moment/or regular javascript methods it adds 7 hours to the time or something? and every time i add UTC hours it adds another day which is not correct either. What can i do? Thanks

julz oh
  • 285
  • 6
  • 17

1 Answers1

0

First you need to get yesterday date and as said in this post you can use:

let date = new Date();

date.setDate(date.getDate() - 1);

Then you can set the hour manually with .setHours() on date object, below example set the hour to midnight for instance:

let date = new Date();

date.setHours(0,0,0,0);

For more information on date Object in javascript you can look the mdn docs

If you combine both you'll have what you're looking for :)

PasNinii
  • 634
  • 8
  • 18
  • Does this return a date object ? I need to use it to query for created At field in my mongodb – julz oh Aug 24 '21 at 14:56
  • `new Date()` returns a Date object, and both `.setDate()`, `.setHours()` modify the object itself. But you can format the date as you want using `.format()` method. I would encourage you to look the docs about Date Object – PasNinii Aug 24 '21 at 15:04
  • It still gives me T07:00 instead of T00:00 – julz oh Aug 26 '21 at 00:21
  • https://stackoverflow.com/questions/3894048/what-is-the-best-way-to-initialize-a-javascript-date-to-midnight/15790005 – PasNinii Aug 26 '21 at 09:01