Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize reads datetime in UTC only

I have set the timezone option to my timezone (Europe/Zagreb and I've tried with +02:00 too), and the time is saved as it should be, however, when reading the time from the database, Sequelize converts it to UTC. I have tried different timezones too, each is saved correctly, but always converted to UTC when read from database.

Am I doing something wrong or is this a known issue and are there any workarounds?

I create a new connection with:

sequelize = new Sequelize(config.database, config.username, config.password, config);

and my configuration looks something like this:

"development": {
    "username": "root",
    "password": "root",
    "database": "db",
    "host": "localhost",
    "dialect": "mysql",
    "timezone": "Europe/Zagreb"
}
like image 413
Vedran Avatar asked Nov 18 '17 15:11

Vedran


3 Answers

You can Try This code, I had the same problem and this worked for me.

const sequelize = new Sequelize(mysql.database, mysql.user, mysql.password, {
    host: mysql.host,
    port:3306,
    dialect:'mysql',
    define: {
      underscored: true,
      freezeTableName: true, //use singular table name
      timestamps: false,  // I do not want timestamp fields by default
    },
    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: '+01:00'
});
like image 96
arpitansu Avatar answered Nov 13 '22 11:11

arpitansu


Maybe timezone is not needed if you use UTC.

For example, my mysql server is timezone '+08:00',

"mysql2": "^1.6.4", "sequelize": "^4.41.2"

const sequelize = new Sequelize(database, username, password, {
    host: hostname,
    port: port,
    dialect: 'mysql',
    dialectOptions: {
        typeCast: function (field, next) {
            if (field.type == 'DATETIME' || field.type == 'TIMESTAMP') {
                return new Date(field.string() + 'Z');
            }
            return next();
        }
    },
    operatorsAliases: false,
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
});
like image 26
Bobby Zhou Avatar answered Nov 13 '22 12:11

Bobby Zhou


You can try this option, that worked for me:

const sequelize = new Sequelize(database, username, password, {
  host: hostname,
  port: port,
  dialect: 'mysql',
  dialectOptions: {
    encrypt: false,
    options: {
      useUTC: false, // for reading from database
    },
  },
  operatorsAliases: false,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});
like image 1
Sanoodia Avatar answered Nov 13 '22 12:11

Sanoodia