Skip to content

Raw queries convert Date replacements to local timezone. #10493

Closed

Description

@stoyaneft

What are you doing?

const Sequelize = require('sequelize');
const sequelize = new Sequelize('mysql://user:pass@localhost:3306/users');

const User = sequelize.define('user', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  username: Sequelize.STRING,
  birthday: Sequelize.DATE(3)
},
{ timestamps: false });

const birthday = new Date('2019-03-01T13:10:16.000Z');

sequelize.query("INSERT INTO `users` (id, username, birthday) VALUES (:id, :username, :birthday)", { 
    replacements: {id: 1, username: 'George', birthday },
    type: sequelize.QueryTypes.INSERT})
  .then(() => {
      User.findOne({where: { id: 1 }, raw: true }).then(user => { 
        console.log(user.birthday, birthday); // 2019-03-01T15:10:16.000Z 2019-03-01T13:10:16.000Z
        console.log(user.birthday.getTime() === birthday.getTime()); // false
      });
  })

What do you expect to happen?

I expected that the date inserted would be exactly the one I passed in the raw query replacements.

What is actually happening?

However, the date is converted to local time before insertion. The following sql statement is executed:

Executing (default): INSERT INTO users (id, username, birthday) VALUES (1, 'George', '2019-03-01 15:10:16')

Dialect: any
Dialect version: XXX
Database version: XXX
Sequelize version: 4.42.1
Tested with latest release: Yes (4.42.1)

Activity

  1. changed the title [-]Raw queries converts Date replacements to local timezone.[/-] [+]Raw queries convert Date replacements to local timezone.[/+] on Mar 2, 2019
  2. 5amfung commented on Apr 26, 2019

    @5amfung

    I'm also running into this problem. The debug logging of the query shows that my input is converted to local time even though it really should be UTC. All the data in the table is UTC as well.

    SELECT labels.id AS id, COUNT(cards.id) AS total_reviews
        FROM labels
          LEFT JOIN card_label ON labels.id = card_label.label_id
          LEFT JOIN cards ON cards.id = card_label.card_id 
          AND cards.next_reminder_at <= '2019-04-25 21:34:54.501 -07:00'
        WHERE labels.user_id = '12345'
        GROUP BY labels.id;
    
  3. danieldkim commented on May 22, 2019

    @danieldkim

    workaround in the meantime, assuming you've JSON-stringified a Date object into a dateJson variable:

    CAST(${dateJson.slice().replace(/Z"/, '"')} as DATETIME(3))
    
  4. german970814 commented on Sep 27, 2019

    @german970814

    Any updates about it?

  5. xCloudx8 commented on Oct 3, 2019

    @xCloudx8

    Same here, it cannot be possible that a library does not behave as you expect. With PostgreSQL there's no problem with date but why there should be a different date behaviour with MySQL?
    That makes no sense, and moreover why there's should be an automatic casting to timezone with MySQL but not with PostgreSQL? It should be a connection option and no casting to timezone at default.

  6. papb commented on Oct 30, 2019

    @papb
    Member

    @xCloudx8 I agree, I've seen a few timezone issues, hopefully they will be sorted out soon :)

  7. added
    type: bug
    topic: dates & times
    on Oct 30, 2019
  8. wondie commented on Oct 10, 2020

    @wondie

    I have to abandon sequelize because of time zone issue.

  9. chirale commented on Apr 1, 2021

    @chirale

    This dirty fix based on above solution by @danieldkim solve the issue acting on a one-level data Object named row with some Date fields.
    Must be solved in core though.

    const fixSequelizeDates = (row) => {
        for (const fieldName of Object.keys(row)) {
            const val = row[fieldName]
            if (typeof val === "object" && val instanceof Date) {
                // @see https://github.com/sequelize/sequelize/issues/7243
                // @see https://github.com/sequelize/sequelize/issues/10493#issuecomment-494615263
                if (val.toISOString().slice(-1) === "Z") {
                    row[fieldName] = new Date(val.toISOString().slice(0, -1))
                }
            }
        }
    }
  10. igolskyi commented on Dec 7, 2021

    @igolskyi

    If you work with timezones, the best way is to store dates in UTC and get them from DB with setting your timezone.
    For correct using queries with timezone, prepare your pg driver, full answer see StackOverflow

    Suppose we make a SQL query, select all User's fields, and "createdAt" in timezone 'Europe/Kiev':

    SELECT "createdAt"::timestamptz AT TIME ZONE 'Europe/Kiev' FROM users WHERE id = 1;
    
    # or with variables
    SELECT "createdAt"::timestamptz AT TIME ZONE :timezone FROM users WHERE id = :id;

    For Sequelize (for User model) it will be something like this:

    sequelize.findOne({
      where: { id: 1 },
      attributes: {
        include: [
          [sequelize.literal(`"User"."createdAt"::timestamptz AT TIME ZONE 'Europe/Kiev'`), 'createdAt'],
          
          // also you can use variables, of course remember about SQL injection:
          // [sequelize.literal(`"User"."updatedAt"::timestamptz AT TIME ZONE ${timeZoneVariable}`), 'updatedAt'],
        ]
      }
    });
  11. mainfraame commented on Jul 19, 2026

    @mainfraame

    Still reproducible on 6.37.8 (current latest v6). Adding the exact call site, since it took a while to track down and this thread doesn't name it.

    The root cause is that injectReplacements never receives the connection's timezone and passes undefined to escape():

    // node_modules/sequelize/lib/utils/sql.js  (v6.37.8) — lines 133 and 153
    const escapedReplacement = (0, import_sql_string.escape)(replacementValue, void 0, dialect.name, true);
    //                                                       ^^^^^^ timeZone

    escape() does accept and honour a timezone — it forwards it straight to the data type:

    // lib/sql-string.js:38
    val = dataTypes[dialect].DATE.prototype.stringify(val, { timezone: timeZone });

    So with undefined, Date replacements get stringified in the host's local zone, and options.timezone (default "+00:00") is ignored for raw queries only. Model operations are unaffected, which is what makes it confusing to diagnose.

    Concretely, with TZ=America/New_York:

    // UI sends 2026-07-19T03:59:59.999Z
    sequelize.query('SELECT ... WHERE createdAt <= :end', {
      replacements: { end: new Date('2026-07-19T03:59:59.999Z') },
    });
    // emitted SQL: createdAt <= '2026-07-18 23:59:59'   <-- 4 hours early, ms dropped

    The instant itself is correct; it's just rendered in the wrong frame, and it's then compared against a column stored in UTC. On UTC hosts local == UTC so nothing is visibly wrong, which is why this tends to surface only on developer machines — in our case as a date-range filter silently dropping every row from the last 4 hours.

    Both replacement styles are affected (named :param at line 133, positional ? at line 153).

    Workaround for anyone landing here: format the value to a string before passing it, so there is no Date left for Sequelize to convert.

    replacements: { end: dayjs.utc(value).format('YYYY-MM-DD HH:mm:ss') }

    Two-line fix, if a v6 patch would be considered — the dialect already holds the instance (this.sequelize is set in its constructor), so the configured value is reachable:

    const escapedReplacement = (0, import_sql_string.escape)(
      replacementValue,
      dialect.sequelize?.options?.timezone,
      dialect.name,
      true,
    );

    We are running this as a yarn patch locally and it resolves the issue with no other behavioural change (on UTC hosts the emitted SQL is byte-identical).

    Happy to open a PR if that is useful — though I appreciate v6 is in maintenance, and I have not verified whether v7 is affected, so this may well already be resolved there by the data types rewrite in #14505.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: dates & timestype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions