knex:select 特定日期范围内的行

knex: select rows that are in certain date range

如何使用 knex 查询 table 中特定日期范围内的 select 行?例如,selecting 过去 7 天的行。

Knex 版本:0.15.0

数据库:PostgreSQL

您可以选择任何方式来查询它们,这里是一种方式:

knex('table')
  .where('createdAt', '>=', '2009-01-01T00:00:00Z')
  .where('createdAt', '<', '2010-01-01T00:00:00Z')

您可以使用 Javascript Date() 对象创建两个不同的时间戳,并将它们转换为字符串。

    const currentDate = new Date()

    // Must convert to strings in case you need to prefix a '0' for single digit months or dates
    const currentYear = "" + currentDate.getUTCFullYear()
    const currentMonth = "" + (currentDate.getUTCMonth() + 1) //month indexed at 0
    const currentDay = "" + currentDate.getUTCDate()
    const currentHour = "" + currentDate.getUTCHours()
    const currentMinute = "" + currentDate.getUTCMinutes()
    const currentSeconds = "" + currentDate.getUTCSeconds()

    //Timestamp format: YYYY-MM-DDTHH:MM:SSZ
    const yesterdayTimestamp = `${currentYear}-` +
      // Ternaries are for prefixing a 0 to return values that are single digit
      `${currentMonth.length === 2 ? currentMonth : '0' + currentMonth}-` +
      `${currentDay.length === 2 ? currentDay : '0' + currentDay}T` +
      `${currentHour.length === 2 ? currentHour : '0' + currentHour}:` +
      `${currentMinute.length === 2 ? currentMinute : '0' + currentMinute}:` +
      `${currentSeconds.length === 2 ? currentSeconds : '0' + currentSeconds}Z`

    const lastWeek = new Date()
    lastWeek.setUTCDate(currentDate.getUTCDate() - 1)
    // Then do same string manipulations to create timestamp string for one week ago...

您也可以使用:

  const from = '2019-01-01';
  const to = '2019-02-02';

  knex('myTable')
    .select()
    .whereBetween('createdAt', [from, to]);

http://knexjs.org/#Builder-whereBetween

如果您使用moment,将很容易实现您想要的效果。 从您拥有的日期字符串创建一个 ISO 8601 格式日期。

let startDate = '2019-01-01';
startDate = moment(startDate).format('YYYY-MM-DDTHH:mm:ssZ');
let endtDate = '2019-10-01';
endDate = moment(endDate).format('YYYY-MM-DDTHH:mm:ssZ');

toISOString()方法将日期格式化为YYYY-MM-DD[T]HH:mm:ss.SSS[Z]格式,可以与knex一起使用来查找时间范围内的记录。但是,我更喜欢 format() 方法而不是 toISOString(),因为 format 方法使用没有毫秒的默认格式 (YYYY-MM-DDTHH:mm:ssZ) 并保持时区偏移量。

现在,您可以在startDateendDate的给定范围内找到相关记录,如下所示,

knex('records')
  .where('created_at', '>=', startDate.toString())
  .where('created_at', '<', endDate.toString())
  .then((rows) => {
     /*
      * perform operations on record
      */
  })
  .catch((e) => {
       console.log(e);
  });

或者,您可以使用 knex 中的 whereBetween() 作为,

knex('records')
  .whereBetween('created_at', [startDate.toString() , endDate.toString()])
  .then((rows) => {
     /*
      * perform operations on record
      */
  })
  .catch((e) => {
       console.log(e);
  });

Note: The createdAt column name is replaced with created_at in the most recent versions of knex. At the time writing this answer i used knex@0.19.1. But still you can use createdAt with older versions of knex.

在您的 Repo 中,只需放置这些 where 子句:

  MODEL.query()
          .where('created_at', '>=', '2009-01-01T00:00:00Z')
          .where('created_at', '<', new Date())
          .orderBy('created_at','desc|asc')

以上代码可用于获取从 2009-01-01 到正在进行的日期的所有记录(您可以将 new Date() 替换为您自己想要记录的日期)。

Ques : How to get 2009-01-01T00:00:00Z from 04/14/2020(MM/DD/YYYY)?

答案:

dateSplit = date.split("/");
            date = `${dateSplit[2]}-${dateSplit[0]}-${dateSplit[1]}`;
            date = date + "T00:00:00.000Z";

注意:不要忘记在 MM/DD/YYYY 中发送日期。它还解决了日期或时间显示为递增或递减的问题。