首页 > 解决方案 > TypeORM:如何在 PostgresSQL 中搜索日期范围?

问题描述

考虑ISO8601日期并希望使用 Typeorm 和 PostgreSQL 进行查询

 if (orderInput.begining && orderInput.ending)
     query.andWhere(`order.createdAt
     BETWEEN to_timestamp(${orderInput.begining} / 1000 )
     AND to_timestamp(${orderInput.ending} / 1000 );
`);

这些是我的论点: "2010-12-24T21:32:33.477Z" "2019-12-24T21:32:33.477Z" 这是底层查询和错误:

query failed: SELECT DISTINCT "distinctAlias"."order_id" as "ids_order_id" FROM (SELECT "order"."id" AS "order_id", "order"."createdAt" AS "order_createdAt"
 FROM "order" "order" INNER JOIN "ware" "ware" ON "ware"."id"="order"."wareId" WHERE "order"."organizationId" = $1 AND "order"."createdAt"
                 BETWEEN Wed Dec 25 2019 01:02:33 GMT+0330 (Iran Standard Time) 
                 AND Wed Dec 25 2019 01:02:33 GMT+0330 (Iran Standard Time) ;) "distinctAlias" ORDER BY "order_id" ASC LIMIT 25 -- PARAMETERS: ["8fd87ced-eb58-4460-b74e-d5a2b1491622"]
error: { error: syntax error at or near "Dec"

我想这是因为参数没有被包裹在''(qoutes)中我不知道如何将参数作为标准ISO8606 Date(typescript)传递给typescript,然后将''(qoutes)传递给PostgreSQL

标签: postgresqltypescriptdatetypeormiso8601

解决方案


Typescript 和 PostgreSQL 都非常了解 ISO8601,PostgreSQL 不需要 to_timestamp()。所以这就像一个 chram:

if (orderInput.begining && orderInput.ending)
    query.andWhere(
       `"order"."createdAt"
    BETWEEN :begin
       AND :end`
    ,{ begin: orderInput.begining, end: orderInput.ending);

注意:在 JavaScript 中,您可以通过以下方式轻松制作 ISO8606 标准日期:

const date = new Date(2020,2,2)
const iso  = date.toISOString()

推荐阅读