I’m trying to get a month’s worth of data using KnexJS, I only have the year and month in the form 20xx-mm.
Here’s my Knex query ..
JavaScript
x
7
1
export function getMonthlyData(yearAndMonth, startingFromDay, roomId) {
2
return db('events')
3
.where('roomId', roomId)
4
.whereBetween('start', [`${yearAndMonth}-${startingFromDay} 00:00:00+00`, `${yearAndMonth}-31 23:59:59+00`])
5
.select();
6
}
7
The issue is, I’m starting at a specific date and going through to the 31’st day, some months have 30 days, some 28 and 29. How do I go about to creating a query that helps me achieve this?
I have tried using SQL’s MONTH function along with Knex’s betweenRaw, but unfortunately, I have only the year and month, and the MONTH function expects a datetime.
Advertisement
Answer
This should solve it
JavaScript
1
9
1
export function getMonthlyData(yearAndMonth, startingFromDay, roomId) {
2
const startDate = `${yearAndMonth}-${startingFromDay}`;
3
return db('events')
4
.where('roomId', roomId)
5
.whereRaw(`start >= (TIMESTAMP '${startDate}')::DATE`)
6
.whereRaw(`start < date_trunc('MONTH', TIMESTAMP '${startDate}' + interval '1 month')::DATE`)
7
.select();
8
}
9