Home » Nodejs » UTC DATE in Sequelize.js

UTC DATE in Sequelize.js

Posted by: admin January 30, 2018 Leave a comment

Questions:

I’m using Sequelize in node.js to save open and close times. I’m also using moment.js to format. Alter a FindOrCreate I’m doing this:

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

This works fine and the time gets formatted to MySQL’s datetime format. The Problem is when I retrieve the time Seqquelize thinks it’s a UTC time and converts it to EST (my server timezone).

I would prefer it to go into the database as UTC and come out the same way. Is there something I’m doing wrong? Why does Sequelize not convert it to UTC on insert but assumes it’s UTC coming out? ALso, is there a way to not have it try to convert to my server timezone?

Answers:

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

As you know postgres stores datetimes in UTC.

The issue, for me, turned out to be not in Sequelize but rather in the pg package.

In order to fix it, place this before your sequelize = new Sequelize() line

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 is doing new Date(stringValue), which returns the date in the server’s timezone, which is wrong (unless it’s in utc itself)

For more info, please refer to this thread:
https://github.com/brianc/node-postgres/issues/429

Questions:
Answers:

I faced the same issue, you are using moment wrong.
You should use moment.utc instead of just moment .

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

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