Skip to content

Instantly share code, notes, and snippets.

@hanipcode
Created December 29, 2023 11:26
Show Gist options
  • Save hanipcode/2faedf12ba7bb2b0bafc17829ecf8559 to your computer and use it in GitHub Desktop.
Save hanipcode/2faedf12ba7bb2b0bafc17829ecf8559 to your computer and use it in GitHub Desktop.
mongodb shell date queries helper
var beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
var yesterday = new Date(Date.now() - 86400000);
var endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
db.model.find({
createdAt: {$gte: beginingOfDay({ timeZone: "America/Chicago", date: yesterday}), $lte: endOfDay({ timeZone: "America/Chicago", date: yesterday})}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment