Fecha y hora entre no funciona en TypeScript con TypeORM en PostgreSQL
Quiero recuperar datos entre un rango de fechas y horas determinado. Cuando intento recuperar datos desde la herramienta DBeaver, devolverá todos los datos. Aquí está la consulta que intenté
SELECT id, "vehicleNo", "vehicleClass", "issuedOn", "modifiedOn", "paidOn","ticketStatusId"
FROM public.ticket where "paidOn" >= '2019-04-16 02:30:00 AM' and "paidOn" <= '2019-04-16 11:30:00 AM';
Pero cuando uso typeorm, entonces no devolverá todos los datos. Aquí está mi código de typeorm
const records = await getConnection().getRepository(Ticket)
.createQueryBuilder("ticket")
.innerJoinAndSelect("ticket.ticketStatus", "ticketStatus")
.where(`ticket.paidOn >= :startDate AND ticket.paidOn <= :endDate
AND ticket.modifiedBy = :email AND ticketStatus.title = :status `,
{ startDate: fromDate, endDate: toDate, email: uemail, status: "Paid"})
.orderBy("ticket.paidOn", "DESC")
.getMany();
aquí está el conjunto de datos correcto que tiene que devolver. (8 registros)
pero sólo está devolviendo 4 registros
Respuesta #1
import { startOfDay, endOfDay } from 'date-fns';
import { Between, Equal } from "typeorm";
//...
let findArgs = {
where:{
date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()),
userId: Equal(ctx.req.session.userId)
}
};
return entity.find(findArgs) as any;
Respuesta #2
Instala la biblioteca: https://date-fns.org/docs/Getting-Started
Después de un ejemplo:
- BeforeDate
- AfterDate
- BetweenDates
// BeforeDate
const BeforeDate = (date: Date) => Between(subYears(date, 100), date);
return await this.connection.getRepository(ExampleEntity)
.find({ createdAt: BeforeDate(new Date()) });
// AfterDate
const AfterDate = (date: Date) => Between(date, addYears(date, 100));
return await this.connection.getRepository(ExampleEntity)
.find({ createdAt: BeforeDate(new Date()) });
// BetweenDates
// TypeORM Query Operators with validation before 2 months and actual date plus one day
const BetweenDates = (date: Date) => Between(subMonths(date, 2), addDays(date, 1));
return await this.connection.getRepository(ExampleEntity)
.find({
where: {
createdAt: BetweenDates(new Date()),
},
});

