Issam Rafihi
Issam Rafihi

Reputation: 432

How to set Knex date to 30 days in the future

I think this question is simple really but I wasn't able to find an answer for it.

In Knex i could set a timestamp in my database with knex.fn.now() However now I have a need to set a date 30 days after now is this as simple as knex.fn.now() + 30 work or is there another trick?

Any help is appreciated even a link to a different source. Thank you in advance

Upvotes: 3

Views: 7906

Answers (2)

xims
xims

Reputation: 1608

Thank you for the previous answer, but that Postgresql example didn't work for me.

When I tried knex.raw(`? + INTERVAL '? day'`, [knex.fn.now(), 30]), I got an error "could not determine data type of parameter"

This worked:

knex.raw(`? + ?::INTERVAL`, [knex.fn.now(), '30 day'])

Upvotes: 2

felixmosh
felixmosh

Reputation: 35553

knex.fn.now() will execute CURRENT_TIMESTAMP function on the db, which returns timestamp in ms from 1/1/1970.

You can use a db built in method for calculating future dates. In MySQL this method calls date_add.

SELECT date_add(now(), INTERVAL 30 day);

With Knex you will need to use the raw method.

knex.select(knex.raw('date_add(?, INTERVAL ? day)', [knex.fn.now(), 30]));

Edit:

In postgress, this query will look like:

  SELECT CURRENT_DATE + INTERVAL '1 day';

so, in Knex it will be:

knex.select(knex.raw(`? + INTERVAL '? day'`, [knex.fn.now(), 30]));

Upvotes: 6

Related Questions