f1nn
f1nn

Reputation: 7047

Sequelize — use UNIX timestamp for DATE fields

Is there a way to force Sequelize use UNIX Timestamp as default time format both for createdAt/updatedAt timestamps and for custom-defined Sequelize.DATE field types?

Thanks!

P.S. I'm using MySQL

Upvotes: 6

Views: 12671

Answers (3)

Adam Fowler
Adam Fowler

Reputation: 1751

While eggyal's answer is the proper way to do things in MySQL, some of us might be working in an environment or team that requires us to use a unix timestamp instead of a datetime / timestamp.

I found that a great way to accomplish this is to use hooks inside of sequelize. At the bottom of each of your models, you can add this code:

{
        tableName: 'Addresses',
        hooks : {
            beforeCreate : (record, options) => {
                record.dataValues.createdAt = Math.floor(Date.now() / 1000);
                record.dataValues.updatedAt = Math.floor(Date.now() / 1000);
            },
            beforeUpdate : (record, options) => {
                record.dataValues.updatedAt = Math.floor(Date.now() / 1000);
            }
        }
    }

This will insert the createdAt and updatedAt fields as unix timestamps.

Upvotes: 8

eggyal
eggyal

Reputation: 125835

At any given moment in time, there are two possible dates (depending on one's position relative to the international date line): that is, converting from a UNIX timestamp to a date requires one to consider the timezone.

For example, the UNIX timestamp 946684800 is 2000-01-01 00:00:00Z. Whilst this represents the first day of the new millenium pretty much everywhere east of the Atlantic, it's still millenium eve everywhere to the west of that ocean. So which date does it represent?

Whilst it's possible to convert from a date to a timestamp, one must define one's own convention for so doing (e.g. represent a given date as midnight in UTC) or else the same date may be represented differently upon each encoding. Generally speaking, this is a bad idea which may have all sorts of unintended consequences.

There is a reason that the DATE data type exists: it is the correct way to store a date. Use it.

Upvotes: 6

cs_alumnus
cs_alumnus

Reputation: 1649

No or at least not yet. CreatedAt is set using the utils.now function in sequelize. That function uses the javascript Date function with no additional arguments. Squelize could be modified to change the way it calls Date but there is no code to do that in the current version. see here

You could however disable the createdAt and other timestamps and use raw queries to set your own. However then you're sacrificing the functionality of sequelize. Best solution is probably to convert those fields to unix time in your business logic before using them.

Upvotes: 1

Related Questions