Selecting rows of `date` in the last 24 hours

Viewed 830

Trying to get rows based on timeframes, so last 24 hours, last 7 days, last 30 days, last 1 year, etc.

Last day being calculated like this

let lastDay = Date.now() - (24 * 60 * 60 * 1000)
lastDay = new Date(lastDay).toISOString()

when using .findMany, etc, in the where would the AND be something like this?

      AND: {
            date: {
              gte: lastDay
            }
          }

So find rows of date that is greater than or equal to the last 24 hours?

1 Answers

You can pass a list of objects in where clause and it would be same as using AND filter condition.

For Filtering based on date you can use Filter Operators like gt/gte/lt/lte.

Given this schema:

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
}

You can pass in an ISO string directly to compare:

let lastDay = Date.now() - (24 * 60 * 60 * 1000);
lastDay = new Date(lastDay).toISOString();

let id = 1;

await prisma.user.findMany({
    where: {
      AND: [
        {
          id: id,
        },
        {
          createdAt: {
            gte: lastDay,
          },
        },
      ],
    },
  });

Here is a reference for using AND filters.

Related