node.jssequelize.jsgraphqlsequelize-cli

Sequelize: Adding a day to the date doesn't work


I have a column updatedAt in my table User which is of Date type, it stores date along with time. I want to query using only date and not datetime. I am using sequelize Sequelize.Op.gt and Sequelize.Op.lt operators to get Users updated on that exact date regardless of time by adding 24 * 60 * 60 * 1000. But the date is not incrementing one day. When I try to subtract, it is working flawlessly. I could add one day only after using getTime() method.

I'm confused as to why it works when subtracting without using getTime() but doesn't work when adding. Could anyone explain?

TL;DR

This works:

[Sequelize.Op.gt]: new Date(new Date(updatedAt) - 24 * 60 * 60 * 1000)
//updateAt: 2018-11-27
//output: 2018-11-26

This doesn't work:

[Sequelize.Op.gt]: new Date(new Date(updatedAt) + 24 * 60 * 60 * 1000)
//updateAt: 2018-11-27
//output: 2018-11-27

And this works:

[Sequelize.Op.lt]: new Date(new Date(updatedAt).getTime() + 24 * 60 * 60 * 1000)
//updateAt: 2018-11-27
//output: 2018-11-28

Solution

  • Let's see your 2nd case step by step
    1. new Date(new Date(updatedAt) + 24 * 60 * 60 * 1000)
    2. new Date(new Date(updatedAt) + 86400000)
    3. new Date('Tue Nov 27 2018 17:34:48 GMT+0800 (Some Region)86400000')
    and Date parser ignored '86400000' part of string from input.
    4. new Date('Tue Nov 27 2018 17:34:48 GMT+0800 (Some Region)')
    Now your input is not modified. Javascript doesn't know are you doing string add or number add. This is your confusing point. On other case integer addition and subtraction operators done properly