Kinda Code
Home/Flutter/TypeORM: Selecting Rows Between 2 Dates

TypeORM: Selecting Rows Between 2 Dates

Last updated: May 03, 2022

The examples below show you how to select records between two given dates in TypeORM. The first one uses the find() function and the second uses query builder.

Here’s the user entity that will have a place in both examples:

// User entity
import { 
   Entity, 
   PrimaryGeneratedColumn, 
   Column, 
   CreateDateColumn 
} from 'typeorm'

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;
 
    @CreateDateColumn()
    createdAt: Date;
}

Using Find Options

This code snippet returns all user accounts that were created between May 03, 2019, and May 03, 2022:

import { Between } from "typeorm";

/* Other code */

const userRepository = dataSource.getRepository(User);
const users = await userRepository.find({
        where: {
            createdAt: Between(
                new Date(2019, 5, 3), 
                new Date(2022, 5, 3)
            ),
        }
})

console.log(users);

/* ... */

Using Query Builder

This code filters out all user accounts that were created from May 03, 2019, to May 03, 2022:

const userRepository = dataSource.getRepository(User);
const users = await userRepository
         .createQueryBuilder('user')
         .where('user.createdAt > :startDate', {startDate: new Date(2019, 5, 3)})
        .andWhere('user.createdAt < :endDate', {endDate: new Date(2022, 5, 3)})
        .getMany();

console.log(users);

That’s it. Further reading:

You can also check out our database topic page for the latest tutorials and examples.