Skip to content

mssql "date" type get the value as the previous day #11597

Open

Description

@dengue8830

Issue Description

For mssql "date" type, retrieves the date as 1 day less than the stored value.

What are you doing?

In db the value is "2019-10-30" but the returned value is "2019-10-29"

The result from db (using the sql query generated by sequelize):
image

The result from sequelize:
image

This is the js code

const userProfile = await UserProfile.findByPk(session.userProfileId);
logger.info(`but the birthday for userprofile ${userProfile.id} is ${userProfile.birthDate}`);

What do you expect to happen?

it should return "2019-10-30"

What is actually happening?

it returns "2019-10-29"

Environment

  • Sequelize version: 5.12.2
  • Node.js version: 11.13.0
  • Operating System: MacOS
  • TypeScript version: 3.1.6

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s): mssql
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Related issues

#10231

Activity

  1. papb commented on Oct 22, 2019

    @papb
    Member

    This look like a timezone issue, have you investigated your DB and sequelize's timezone settings?

  2. added
    status: awaiting response
    on Oct 22, 2019
  3. added
    topic: dates & times
    on Oct 30, 2019
  4. dengue8830 commented on Nov 12, 2019

    @dengue8830
    Author

    sorry i didn't get the comment notification.

    yea! a moment timezone problem here

    this snippet is so important at the very first entry point of your app otherwise it will take the local timezone, my server was in Brazil and my localhost in Argentina so it was driving me crazy

    import * as moment from 'moment-timezone';
    moment.tz.setDefault('UTC');
    
  5. papb commented on Nov 13, 2019

    @papb
    Member

    @dengue8830 Thanks for posting it, I will leave this open as a docs issue, it might be a good thing to mention somewhere in the docs!

  6. reopened this on Nov 13, 2019
  7. added
    status: wip
    docs
    and removed
    status: awaiting response
    on Nov 13, 2019
  8. self-assigned this
    on Nov 13, 2019
  9. dengue8830 commented on Nov 14, 2019

    @dengue8830
    Author

    good to know!

  10. papb commented on Dec 23, 2019

    @papb
    Member

    Hi @dengue8830, actually I tried to reproduce your problem in order to make a good clarification of things in the documentation, but I was not able to reproduce it at all... I tried to force my database into a timezone by SET TIMEZONE TO 'CET' for example but it didn't work.

    Is there any chance you can provide an SSCCE for this? That would be great, thanks!

  11. added
    status: awaiting response
    and removed
    status: wip
    on Dec 23, 2019
  12. dengue8830 commented on Dec 24, 2019

    @dengue8830
    Author

    Did you use moment-timezone or just moment?

    Your OS timezone was different of the DB timezone?

    Your DB timezone was UTC?

  13. papb commented on Jan 16, 2020

    @papb
    Member

    I don't remember 😅

    Please try to construct a sequelize-sscce, this will really help me, since I am so short on time...

  14. removed their assignment
    on Jan 16, 2020
  15. kippllo commented on Aug 21, 2020

    @kippllo

    I am having the same issue.
    I think this is a bug and should be fixed, not have a workaround added to the doc.

    I believe the core of this issue effects more dialects than just MSSQL.

    The issue is that all dialects should implement timezone in some way like MySQL does in the file sequelize/src/dialects/mysql/data-types.js in the functions DATE._stringify() & DATE.parse().

    But if you inspect the mssql version of this file sequelize/src/dialects/mssql/data-types.js the function DATE.parse() does not even exist, much less apply options.timezone.
    Because DATE.parse() (or DATEONLY.parse()) do not apply the timezone via moment.js this causes mssql DATEONLY fields to be read a day behind if you are in a UTC-05:00 timezone like I am.

    The easy work around is as @dengue8830 suggested:

    const moment = require('moment');
    ...
    moment.tz.setDefault('UTC');

    If you set moment.js's default timezone to UTC, it will no longer try to modify DATEONLY fields read from the DB.
    THIS IS A SEQUELIZE BUG because I should be able to set options.timezone to fix this issue.
    Or better yet, since mssql server's don't really have a timezone you should account for this automatically without the user needing to change options.timezone.

  16. kippllo commented on Aug 21, 2020

    @kippllo

    Further, I believe these other issues are related because whatever dialect does not fully support sequelize.options.timezone specifically inside of sequelize/src/dialects/{SOME_DIALECT}/data-types.js in the DATE & DATEONLY parse functions:

  17. kippllo commented on Aug 21, 2020

    @kippllo

    To be clear, the only reason this is an issue with MSSQL specifically, is because DATEONLY.parse() uses:

    class DATEONLY extends BaseTypes.DATEONLY {
        static parse(value) {
          return moment(value).format('YYYY-MM-DD');
        }
      }

    The line moment(value).format('YYYY-MM-DD') uses whatever timezone is set in moment.js. Which by default is the local system timezone. This causes the DATEONLY field to read incorrectly since MSSQL does not store a global timezone.

    I believe this function should incorporate timezone (which should default to 'UTC' for mssql) like
    sequelize/src/dialects/mysql/data-types.js's function does:

    class DATE extends BaseTypes.DATE {
        static parse(value, options) {
          value = value.string();
          if (value === null) {
            return value;
          }
          if (moment.tz.zone(options.timezone)) {
            value = moment.tz(value, options.timezone).toDate();
          } else {
            value = new Date(`${value} ${options.timezone}`);
          }
          return value;
        }
      }
  18. github-actions commented on Nov 6, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  19. paulish commented on Apr 19, 2023

    @paulish

    Similar problem with saving '1981-04-01' with Europe/Moscow timezone. The value is saved as '1981-03-31'. The only workaround I found is to add 1 hour to param and pass it as Date with validate = false option set.

    I suppose it is not needed to convert string value at all but it is converted by the following code

    class DATEONLY extends ABSTRACT {
      ...
      _stringify(date) {
        return moment(date).format("YYYY-MM-DD");
      }
    ...
    }
    

    The DATEONLY._stringify should check if passed date is Date at all. And if it is already a string then prevent the conversion.

  20. removed
    status: awaiting response
    on Apr 19, 2023
  21. klondikemarlen commented on Jan 11, 2024

    @klondikemarlen

    I get this issue type: DataTypes.DATEONLY, fields with [email protected], when using MSSQL with TZ=America/Whitehorse (-07:00). Interestingly enough the time of day doesn't seem to matter.

    The issue is fixed by setting the to TZ=UTC in a node:18.17.0-alpine3.17 docker image.

    Using this schema field description

    paidOn: {
      type: DataTypes.DATEONLY,
      allowNull: false,
      get() {
        console.log(
          "this.getDataValue('paidOn'):",
          JSON.stringify(this.getDataValue("paidOn"), null, 2)
        )
        console.log("this.getDataValue('paidOn'):", this.getDataValue("paidOn"))
        console.log("this.getDataValue('paidOn'):", typeof this.getDataValue("paidOn"))
        return this.getDataValue("paidOn")
      },
    },

    reveals the interesting fact that paidOn, originally set as 2023-04-01, is actually a string, and is one day early even at this point. The raw value is incorrect.

    this.getDataValue('paidOn'): "2023-03-31"
    this.getDataValue('paidOn'): 2023-03-31
    this.getDataValue('paidOn'): string
    

    The "bug" is that when saving the value as 2023-04-01, in the America/Whitehorse timezone, the value is retrieved as 2023-03-31. Since there isn't any timezone information attached to a date only value 2023-04-01 I would expect Sequelize to return the same value that I saved, regardless of what my timezone is.

    I guess the issue could be solved by using a string field, but that seems ... unfortunate.

  22. pulinjhaveri commented on Jun 20, 2024

    @pulinjhaveri

    Buddy,
    For MSSQL, change useUTC to false :
    Change your config for connecting:

    environment: { username: 'a', password: 'b', database: 'c', 
    dialectOptions: { 
    useUTC: false, // for reading from database 
    },
    options: {
    useUTC: false,
    },
     timezone: '+05:30', // for writing to database 
    },
    
  23. LeonxLJX commented on Sep 2, 2026

    @LeonxLJX
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

    docstopic: dates & times

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions