简体   繁体   中英

sequelize compare date with date-timestamp

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?

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.

Simply you can do it like

createdAt:{[Op.between]:[moment().startOf("day").toDate(),moment().endOd("day").toDate()]}

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,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM