Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store local date time in sequelize?

I am using the version 2.0.0-rc8 of sequelize. When i stored the local date time, it always stores UTC date time. Is it possible to store local date time using sequelize?

like image 902
Gurpinder Avatar asked Feb 09 '15 13:02

Gurpinder


People also ask

How do you find the current date and time Sequelize?

sequelize. query('SELECT CURRENT_TIMESTAMP AS time'); it returns the date/time in UTC.


2 Answers

As others have already hinted in the comments, sequelize converts the date to UTC - this is by design, because it makes it easier for sequelize to work with, and to ensure that sequelize clients in different timezones will see the same timestamp.

In javascript the date will always be in the server's local time - this is a property of the javascript date object.

You can tell sequelize to store the date in a different timezone by using the timezone option:

new Sequelize(db, user, pass, {
  timezone: '+01:30'
});

This will save all dates with that timezone and also assume that all dates currently saved in the DB are in that timezone

like image 98
Jan Aagaard Meier Avatar answered Oct 12 '22 23:10

Jan Aagaard Meier


Maybe you should correctly store UTC time in mysql so that timezone is not needed.

For example, my mysql server is in timezone '+08:00', but if I change the timezone to '-05:00' the action will not break anything.

just use sequelize like this:

"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 38
Bobby Zhou Avatar answered Oct 13 '22 00:10

Bobby Zhou