Sequelize set timezone to query
Solution 1
This is how I configured it:
dialectOptions: {
dateStrings: true,
typeCast: true,
},
timezone: 'America/Los_Angeles',
http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html
Solution 2
I suggest combining moment.js with one of the following methods:
If you need to parameterize the timezone, then you will probably want to add the offset for each individual query or add an additional field to your table that indicates the timezone, as it does not seem as though sequelize allows parameterized getters.
For example:
const moment = require('moment.js');
const YourModel = sequelize.define('your_model', {
created_at: {
type: Sequelize.DATE,
allowNull: false,
get() {
return moment(this.getDataValue('created_at'))
.utcOffset(this.getDataValue('offset'));
},
},
});
Another possibility would be to extend the model prototype's instance methods in a similar fashion, which allows you to specify the offset at the time that you require the created_at value:
const moment = require('moment.js');
YourModel.prototype.getCreatedAtWithOffset = function (offset) {
return moment(this.created_at).utcOffset(offset);
};
![Danis](https://i.stack.imgur.com/ELXGQ.jpg?s=256&g=1)
Danis
Updated on June 14, 2022Comments
-
Danis about 2 years
I'm currently using the Sequelize with postgres in my project. I need to change the query, so it return created_at column with timezone offset.
var sequelize = new Sequelize(connStr, { dialectOptions: { useUTC: false //for reading from database }, timezone: '+08:00' //for writing to database
});
But this affects on entire database. But I need to use timezone for select queries only. Does anyone know how to do that?
-
Luke Galea over 3 yearsWhatever I set time zone to, in phpmyadmin I still get created_at and updated_at times of my server. Clicking on the field also shows the incorrect time zone. What could I be doing wrong?
-
Developerium over 3 yearsMaybe it's just a representational thing
-
Martin Naughton over 3 yearsDoes this work with postgres? I have tried it and it has not worked. I have tried a few ways but timezone setup does not seem to work with sequelize and postgres
-
hsyn.ozkara almost 2 yearsthis code save my a lot of times. Thanks // we must store dates in UTC pg.defaults.parseInputDatesAsUTC = true