Skip to content

Setting timezone #854

Open

Description

@nczz

how can i use this option correct? and this option is not showing in doc.

sequelize    = new Sequelize(config.database, config.username, config.password, { timezone : "+08:00", pool:config.pool, dialect: 'mysql', logging: false, host: config.host})

it not working...

Activity

  1. nczz commented on Aug 23, 2013

    @nczz
    Author

    Sorry.. I find my problem!
    timestamp is UTC format in DB, So I just need add "UTC" flag in convert to local time.

    Maybe write it in document can avoid next issue like me... Orz

  2. joakimbeng commented on Nov 21, 2013

    @joakimbeng

    I've run into this as well and would like to know how to set timezone...
    @nczz what do you mean with:

    So I just need add "UTC" flag in convert to local time

    Where is that, i.e. where can one set a flag for date conversions?

  3. nczz commented on Nov 22, 2013

    @nczz
    Author

    @joakimbeng There is no timezone setting in sequelize. You can just add a flag "UTC" with timestamp to convert in JS.

    In DB, It stored like 2013-11-22 07:26:53 .

    Convert example:

    var LOCALTIME = new Date(DATA_FROM_DBMS+"UTC");
  4. janmeier commented on Nov 22, 2013

    @janmeier
    Member

    @joakimbeng @nczz is correct. There is currently no way to enforce a timezone in sequelize. Sequelize simply assumes that your data is in UTC (which should be more clearly documented, see sequelize/doc#92)

    Short clarification (taken from another thread #1035)

    I originally rewrote the date logic to UTC, so I would like to elaborate on why I think this is the correct behavour. Mind you I haven't looked at the code lately, so im just speaking from memory :).

    The two dates you posted represent the same point in time:

    d1 = new Date('2013-11-02 00:00:00Z')
    Sat Nov 02 2013 01:00:00 GMT+0100 (W. Europe Standard Time)
    d2 = new Date('Sat Nov 01 2013 22:00:00 GMT-0200 (BRST)')
    Sat Nov 02 2013 01:00:00 GMT+0100 (W. Europe Standard Time)
    
    d1.getTime()
    1383350400000
    d2.getTime()
    1383350400000
    d1.getTime() === d2.getTime()
    true

    Model.date is a javascript Date object, and those are always in the local timezone. If you want to the get the UTC time of a Date, you will have to write custom logic using .getUTCDate() etc. When you pass a date object to sequelize it is converted to UTC before it is saved, not matter what local time zone it has. When you retrieve a date object is created, representing the UTC timestamp in the local timezone of your server. This means that even if you save a date from a server in one timezone and retrieve it from a server in another zone, the date objects will represent the same point in time (their timestamps are equal), even though their .toString() representation will be different.

    In short you should not take extra care to convert your dates to UTC before passing them to sequelize, sequelize will handle the conversion.

    end

    So in short, when a date is retrieved from the DB, it is assumed to be in UTC when it is converted to a javascript date object. Correspondingly, when a date object is saved it is converted from the local timezone of the server to UTC.

    If you still need the ability to set timezone, please make a new feature request.

  5. tomwang1013 commented on Nov 19, 2014

    @tomwang1013

    @janmeier I think the problem exists.
    d1 = new Date('2013-11-02 00:00:00Z')
    You added Z which change the time making it different from the one in mysql.

  6. janmeier commented on Nov 19, 2014

    @janmeier
    Member

    @tomwang1013 see my comment in #2590 - you can manually overridethe timezone

  7. diosney commented on Sep 28, 2016

    @diosney
    Contributor

    @janmeier Your previous explanation saved me from a very nasty bug with moment due a confusion between local and UTC dates.

    It would be nice to have it in the official docs ;) specially the end paragraph, since were really helpful to me and there are a lot of people out there having issues with this too.

  8. cherchyk commented on Mar 20, 2017

    @cherchyk

    sequelize converts time to my local zone when it reads from DB.

    How to disable automated conversion?

    I tried timezone : "+08:00" but values was not changed.

  9. lovelyelfpop commented on Apr 15, 2017

    @lovelyelfpop

    timezone : "+08:00" only has effect on writing date to database, not reading from database

  10. lovelyelfpop commented on Apr 17, 2017

    @lovelyelfpop
    var sequelize = new Sequelize(connStr, {
        dialectOptions: {
            useUTC: false //for reading from database
        },
        timezone: '+08:00' //for writing to database
    });
    
  11. feiZhang commented on Apr 26, 2017

    @feiZhang

    @lovelyelfpop
    https://github.com/mysqljs/mysql
    没有 useUTC

    貌似
    dialectOptions: {
    dateStrings: true, //禁止mysql的转换
    typeCast: true //覆盖了sequelize的转换,看代码,目前只影响date和GEOMETRY,能用
    }
    的话,能用。避免了,显示时格式化时间的问题。
    废了半天劲,以为只是sequelize变换的,原来是mysql库自己也在变换的。

    不知道大神,有没有更好的方法,一个一个字段设置get,感觉好不爽。

  12. catalsdevelop commented on Aug 2, 2017

    @catalsdevelop

    a fancy solution is to custom your own cast function when a DATETIME type field found.

    var sequelize = new Sequelize(connStr, {
        typeCast: function (field, next) { // for reading from database
          if (field.type === 'DATETIME') {
            return field.string();
          }
          return next();
        },
        timezone: '+08:00' // for writing to database
    });
  13. ernani commented on Aug 17, 2017

    @ernani

    Does hardcoding the timezone accounts for DST settings? Thanks!

  14. RichAyotte commented on Sep 9, 2017

    @RichAyotte

    Make sure the timezone is the same everywhere.

    const timezone = 'UTC'
    process.env.TZ = timezone
    
    const db = {
      options: {
        dialectOptions: {
          timezone
        }
        , timezone
      }
    }

    EDIT: Setting the environment variable TZ within the app is not always a good idea. Set it the way that is most appropriate for your needs. Perhaps use .env or in a launch script.

  15. 38 remaining items

  16. danielimas commented on Nov 10, 2021

    @danielimas

    @Angatupyry Have you tried removing the useUTC option? I get a warning when using it, stating that it is an invalid dialectOption. Additionally, I'm setting my timezone as it follows: -07:00. The code sample lies down below.

        dialectOptions: {
          dateStrings: true,
          typeCast: (field: any, next: any) => {
            if (field.type === "DATETIME") {
              return field.string();
            }
            return next();
          },
        },
        timezone: process.env.TIMEZONE || "-00:00",
  17. saefullohmaslul commented on Oct 19, 2022

    @saefullohmaslul

    @mike-seekwell This is still working for me in 2021 when working with postgres. I want to set the timezone in the session so it would convert columns "timestamp with time zone" to correct time based on a timezone. None of the sequelize configuration for setting the time zone worked from the document. I was only interested in the read to convert UTC.
    https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html
    A sample method to use to set the timezone before you run a sequel query.

    module.exports.setTimeZone = function (timezone = '0000') {
      const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
      require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
        return new Date(stringValue + timezone); // '+0100'
      });
    };
    

    Thanks for the save mike.

    At what point should I add this function?

    Sorry, i just applied that code in my project, what you can do is this, create a file with the function

    file.js

    export const setTimeZone = function(timezone = '0000') {
        const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
        require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
            return new Date(stringValue + timezone)
        })
    }

    and then, in your main function, where you start the app, import that const and call it like this in order to establish the timeZone as soon as you init the app

    index.js

    import app from './app';
    import { setTimeZone } from 'file.js'; // depends on where you create your file
    
    async function main(){
      await app.listen(8000);
      console.log('Server on port 8000');
      setTimeZone("+0000")  // <===
    }
    main();

    Now when you read the database info won't add extra hours

    And this seems to work at least for writing data

    const sequelize = new Sequelize(connectionString, {
      timezone: 'America/Asuncion'  // <=== this option
    });

    its work for me on nestjs + sequelize

  18. stringang commented on Nov 11, 2022

    @stringang

    env:

    I want to record the UTC time in the database and return the local time zone time when querying the database, which I have done with the following configuration.

    1. define the column type as a literal "DATETIME":
      @CreatedAt
      @Column({ type: "DATETIME" })  // <=== convert to utc time
      createdAt: Date;
    
    1. connection Options:
    SequelizeModule.forRoot({
      dialect: 'mysql',
      host: '127.0.0.1',
      logQueryParameters: true,
      timezone: '+08:00',  // <=== for writing to database
      dialectOptions: {
        timezone: '+08:00',
        typeCast: function (field, next) { // <=== for reading from database
          if (field.type == 'DATETIME' || field.type == 'TIMESTAMP') {
            return new Date(field.string() + 'Z');
          }
          return next();
        }
      }
    }),
    

    reference: https://sequelize.org/api/v7/interfaces/options#timezone

  19. xafixav commented on Mar 31, 2023

    @xafixav

    @mike-seekwell This is still working for me in 2021 when working with postgres. I want to set the timezone in the session so it would convert columns "timestamp with time zone" to correct time based on a timezone. None of the sequelize configuration for setting the time zone worked from the document. I was only interested in the read to convert UTC.
    https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html
    A sample method to use to set the timezone before you run a sequel query.

    module.exports.setTimeZone = function (timezone = '0000') {
      const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
      require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
        return new Date(stringValue + timezone); // '+0100'
      });
    };
    

    Thanks for the save mike.

    At what point should I add this function?

    Sorry, i just applied that code in my project, what you can do is this, create a file with the function

    file.js

    export const setTimeZone = function(timezone = '0000') {
        const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
        require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
            return new Date(stringValue + timezone)
        })
    }

    and then, in your main function, where you start the app, import that const and call it like this in order to establish the timeZone as soon as you init the app

    index.js

    import app from './app';
    import { setTimeZone } from 'file.js'; // depends on where you create your file
    
    async function main(){
      await app.listen(8000);
      console.log('Server on port 8000');
      setTimeZone("+0000")  // <===
    }
    main();

    Now when you read the database info won't add extra hours

    And this seems to work at least for writing data

    const sequelize = new Sequelize(connectionString, {
      timezone: 'America/Asuncion'  // <=== this option
    });

    It worked for me, thx.
    I made a few changes for typescript, just posting for help people in future:

    Installed types for pg

    npm i --save-dev @types/pg
    
    import pg from 'pg';
    
    export const setTimeZone = function(timezone = '0000') {
      const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
      pg.types.setTypeParser(TIMESTAMPTZOID, stringValue => {
          return new Date(stringValue + timezone)
      })
    }

    added the import into the app class.

    import { setTimeZone } from './timezone';

    attached the method inside the Start in app class.

      public start(PORT: string | number):void {
        this.app.listen(Number(PORT), () => console.log(`Servidor ouvindo na PORTA: ${PORT}`));
        setTimeZone('+0000')
        this.apiMethods();
      }

    worked on sequelize + express

    Wanna thanks @mike-seekwell and @JoseMMC99 , huge help.

  20. ledihildawan commented on Apr 5, 2023

    @ledihildawan
    var sequelize = new Sequelize(connStr, {
        dialectOptions: {
            useUTC: false //for reading from database
        },
        timezone: '+08:00' //for writing to database
    });
    

    Hi, this worked for me, thanks. But I have another question. Will there be another problem later when someone will filter based on a different time (time zone) than me?

  21. HamzaTatheer commented on Jul 3, 2023

    @HamzaTatheer

    does this issue still exists ? does sequelize give the option to store date as well as timezone ( by extending the model class in Typescript ). Currently, It only gives option to store date. As a result, extra code needs to be written in order to store timezone besides date.

    Is any contribution for this welcomed ?

  22. ephys commented on Jul 3, 2023

    @ephys
    Member

    The problem with that is that there are no zoned datetime type available in any(?) database

    See #14295

  23. CapDuan commented on Sep 6, 2023

    @CapDuan

    What works for me is in this stack overflow answer

    const sequelize = new Sequelize(connectionString, {
    dialectOptions: {
          useUTC: false, //for reading from database
          dateStrings: true,
    
          typeCast: function (field, next) { // for reading from database
            if (field.type === 'DATETIME') {
              return field.string()
            }
            return next()
          },
        },
        timezone: "Asia/Kuala_Lumpur"
      });
    

    thx

  24. N1ghtHunter commented on Oct 11, 2023

    @N1ghtHunter

    @mike-seekwell This is still working for me in 2021 when working with postgres. I want to set the timezone in the session so it would convert columns "timestamp with time zone" to correct time based on a timezone. None of the sequelize configuration for setting the time zone worked from the document. I was only interested in the read to convert UTC.
    https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html
    A sample method to use to set the timezone before you run a sequel query.

    module.exports.setTimeZone = function (timezone = '0000') {
      const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
      require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
        return new Date(stringValue + timezone); // '+0100'
      });
    };
    

    Thanks for the save mike.

    At what point should I add this function?

    Sorry, i just applied that code in my project, what you can do is this, create a file with the function
    file.js

    export const setTimeZone = function(timezone = '0000') {
        const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
        require('pg').types.setTypeParser(TIMESTAMPTZOID, stringValue => {
            return new Date(stringValue + timezone)
        })
    }

    and then, in your main function, where you start the app, import that const and call it like this in order to establish the timeZone as soon as you init the app
    index.js

    import app from './app';
    import { setTimeZone } from 'file.js'; // depends on where you create your file
    
    async function main(){
      await app.listen(8000);
      console.log('Server on port 8000');
      setTimeZone("+0000")  // <===
    }
    main();

    Now when you read the database info won't add extra hours
    And this seems to work at least for writing data

    const sequelize = new Sequelize(connectionString, {
      timezone: 'America/Asuncion'  // <=== this option
    });

    It worked for me, thx. I made a few changes for typescript, just posting for help people in future:

    Installed types for pg

    npm i --save-dev @types/pg
    
    import pg from 'pg';
    
    export const setTimeZone = function(timezone = '0000') {
      const TIMESTAMPTZOID = 1184; // https://docs.huihoo.com/doxygen/postgresql/interfaces_2ecpg_2ecpglib_2pg__type_8h.html
      pg.types.setTypeParser(TIMESTAMPTZOID, stringValue => {
          return new Date(stringValue + timezone)
      })
    }

    added the import into the app class.

    import { setTimeZone } from './timezone';

    attached the method inside the Start in app class.

      public start(PORT: string | number):void {
        this.app.listen(Number(PORT), () => console.log(`Servidor ouvindo na PORTA: ${PORT}`));
        setTimeZone('+0000')
        this.apiMethods();
      }

    worked on sequelize + express

    Wanna thanks @mike-seekwell and @JoseMMC99 , huge help.

    This doesn't work as expected when making updates to the rows
    updatedAt values appear non-changed by the time zone only createdAt do
    example:
    { "inventoryItem": { "id": 3, "name": "Pepsi", "price": 10, "quantity": "5", "createdAt": "2023-10-11T06:41:53.282Z", "updatedAt": "2023-10-11T03:55:39.654Z" } }
    expected :
    { "inventoryItem": { "id": 3, "name": "Pepsi", "price": 10, "quantity": "5", "createdAt": "2023-10-11T06:41:53.282Z", "updatedAt": "2023-10-11T06:55:39.654Z" } }

  25. mohammadrz003 commented on Dec 29, 2023

    @mohammadrz003

    for me, the problem was the Postgres configuration itself.
    on Windows OS, go to the file located in C:\Program Files\PostgreSQL\<POSTGRES VERSION>\data\postgresql.conf and look for the two variables below and change them to your needs.
    log_timezone = 'UTC'
    and
    timezone = 'UTC'

    then, run this query to reload the config:
    select pg_reload_conf()

    to confirm the changes:
    show timezone

    source: https://stackoverflow.com/a/72116384/17222362

  26. dallasrevolt commented on Jul 8, 2024

    @dallasrevolt

    I've tried all of the suggested solutions, but it does not work for me. I am using PostgreSQL v14 on Ubuntu 22.04. When I send a request with Postman, it always returns the DATE with UTC.

  27. added theissue type on Mar 9, 2025
  28. removed
    type: feature
    on Mar 9, 2025
  29. 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

    docsexisting workaroundstatus: in discussiontopic: dates & times

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions