knex: select rows that are in certain date range

You can just create two different timestamps using Javascript Date() object, and convert them to strings.

    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...

Any way you choose to query them should do, here is one way to do it:

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

If you are using moment, it will be pretty easy to achieve what you want. create an ISO 8601 format date from the date string you have.

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() method will format the date in YYYY-MM-DD[T]HH:mm:ss.SSS[Z] format, which can be used with knex to find the record in time range. However, I prefer the format() method over toISOString() because format method uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

Now, you can find the relevant records in the given range of startDate and endDate as given below,

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

or alternatively, you can use whereBetween() from knex as,

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 [email protected]. But still you can use createdAt with older versions of knex.


You can also use :

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

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

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