Reputation: 7145
my simple use case is I pass a date
and try to compare that with the default createdAt
column.
where: {
createdAt: {
$eq: date
}
}
and my date is a string like this date = '2018-12-12'
The problem here is sequlize not compare only the date. But it does add time 00:00:00 to my date and then compare. So the query sequlize generate is like this.
WHERE `redeem_points`.`createdAt` = '2018-11-02 00:00:00';
What I deserved
WHERE `redeem_points`.`createdAt` = '2018-11-02';
How do I achieve this using sequlize?
Upvotes: 1
Views: 1687
Reputation: 22
Simply you can do it like
createdAt:{[Op.between]:[moment().startOf("day").toDate(),moment().endOd("day").toDate()]}
Upvotes: 1
Reputation: 144
I have used a moment.js lib, but of course, you can get the start and end of the day using the JS functionality. you also need to check timezone.
let condition = {};
// For the case when you want to get a data for the specific date
// if (date) {
// condition.createdAt = {
// [Op.and]: [
// {
// [Op.gte]: moment(date)
// .startOf("day")
// .format("YYYY-MM-DDTHH:mm:ss.SSS[Z]"),
// },
// {
// [Op.lte]: moment(date)
// .endOf("day")
// .format("YYYY-MM-DDTHH:mm:ss.SSS[Z]"),
// },
// ],
// };
// }
// If you want to get a data for the current day
condition.createdAt = {
[Op.and]: [
{
[Op.gte]: moment().startOf("day").toDate(),
},
{
[Op.lte]: moment().endOf("day").toDate(),
},
],
};
ActivityLog.findAll({
where: condition,
});
Upvotes: 0
Reputation: 1619
I think you would want something more like:
{
where: {
createdAt: { [Op.like]: `${date}%`, },
}
}
Which would give SQL syntax like (note the wildcard):
WHERE createdAt LIKE '2018-11-02%'
Operators can give you a broad range of SQL syntax equivalents, additionally I think the shorthand you are using is deprecated so I subbed in the Op
syntax you might need that as sequelize.Op
if you aren't destructuring your variables.
Upvotes: 1