Search code examples
javascriptnode.jsdayjsknex.js

KnexJS select all records from current year


I just want to be able to select all records from this current year, like, we're in 2020, select all records which created_at year is greater than 2020.

const current_year = dayjs().format('YYYY');

I'm using dayjs to get the current year. How can i compare the row year of creation with the current year with knexjs?


Solution

  • You can use Year function of your DB (I guess that it has it, MySql has it).

    const current_year = dayjs().format('YYYY');
    
    const results = await knex('tableName').whereRaw('Year(dateCreated) = ?', [current_year]);
    

    This will execute

    Select * from tableName Where Year(dateCreated) = `2020`;