UTC DATE at Sequelize.js

I use Sequelize in node.js to save open and close time. I also use format.js for formatting. Alter FindOrCreate I am doing this:

result.open = moment(hours.open, "hh:mma").format("YYYY-MM-DD HH:mm:ss"); result.save() ... 

This works great and time is formatted in MySQL datetime format. The problem is that I am extracting the time when Seqquelize considers this to be UTC and converts it to EST (my server time zone).

I would prefer it to enter the database as UTC and exit in the same way. Is there something I'm doing wrong? Why doesn't Sequelize convert it to UTC on the inset, but assumes UTC will come out? Also, is there a way to not try to convert it to the server time zone?

+6
source share
3 answers

I know this is pretty late, but here for those struggling with this postgres (maybe this may point you in the right direction for other engines)

As you know, postgres store data in UTC.

The problem, for me, was not in Sequelize, but in the pg package.

To fix this, put this in front of your line sequelize = new Sequelize()

 var types = require('pg').types; var timestampOID = 1114; types.setTypeParser(1114, function(stringValue) { return new Date( Date.parse(stringValue + "0000") ); }); 

The problem, I think, is that the pg package executes new Date(stringValue) , which returns the date in the server time zone, which is wrong (unless it is in utc)

For more information, see this topic: https://github.com/brianc/node-postgres/issues/429

+4
source

I ran into the same problem, you are using the moment incorrectly. You should use moment.utc instead of moment .

Take a look at the documentation: http://momentjs.com/docs/#/parsing/utc/

 result.open = moment.utc(hours.open, "hh:mma").format("YYYY-MM-DD HH:mm:ss"); result.save() 
0
source

I had the same problem. I fixed it as follows:

config/sequelize.js :

 const sequelize = new Sequelize(database, user, password, { host, dialect: 'mysql', port, operatorsAliases, dialectOptions: { useUTC: true, // -->Add this line. for reading from database }, timezone: '+02:00', // -->Add this line. for writing to database pool: { max: 10, min: 0, idle: 10000, }, logging: console.log, // define: {}, }) 

momentJS (UTC):

 const ACCEPT_FORMAT = 'YYYY-MM-DD hh:mm:ss' const { start_date, end_date } = req.params const start = moment.utc(start_date, ACCEPT_FORMAT) const end = moment.utc(end_date, ACCEPT_FORMAT) console.log(start) console.log(end) 

Hope this helps someone .... :)

0
source

Source: https://habr.com/ru/post/950741/


All Articles