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:
- TypeORM: Selecting Rows with Null Values
- TypeORM: AND & OR operators
- TypeORM: How to Limit Query Execution Time
- Using ENUM Type in TypeORM
- Best open-source ORM and ODM libraries for Node.js
- TypeORM: Adding Fields with Nullable/Default Data
You can also check out our database topic page for the latest tutorials and examples.