I am using knex to get a list of clients with their birth dates on mysql. I want to get only clients that are having birthday on the next month. I think the best way is to compare dates ignoring the year, but I can't find anywhere how to do that. I don't know if there is a better ways to get the birthdate..
let date1 = moment(new Date(), "DD/MM");
let date2 = moment(new Date(), "DD/MM").add(1, "M");
function getClients(req, res){
app.db('.clients')
.select(clients.*)
.modify(function (queryBuilder) {
queryBuilder
.format('clients.birth', 'DD-MM')
.where('clients.birth', '>=', date1).andWhere('clients.birth', '<=', date2)
})
.then(clients => res.json(clients))
}
CodePudding user response:
I was able to make it work using the .whereRaw with the EXTRACT MONTH and EXTRACT DAY from the sql.
let today = moment(new Date(), "DD/MM/YYYY");
let next_month = moment(today).add(1, "M");
let present_month = moment(today).format("MM");
today = moment(today).format("DD")
next_month = moment(next_month).format("MM");
function getClients(req, res){
app.db('.clients')
.select(clients.*)
.where(function (qb) {
qb
this.whereRaw(`EXTRACT(MONTH FROM clients.birth) = ?`, [present_month])
.andWhereRaw(`EXTRACT(DAY FROM clients.birth) > ?`, [today])
})
.orWhere(function (qb) {
qb
this.whereRaw(`EXTRACT(MONTH FROM clients.birth) = ?`, [next_month])
.andWhereRaw(`EXTRACT(DAY FROM clients.birth) < ?`, [today])
})
.then(clients => res.json(clients))
}
That way I get the clients who are having a birthday within 1 month from the request date.