Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 973
f1nn Avatar asked Oct 02 '13 14:10

f1nn


People also ask

How do I use timestamp in Sequelize?

If you want to use the TIMESTAMP type, then you need to manually specify the attributes as TIMESTAMP types in your model as shown below: const User = sequelize. define( "User", { firstName: Sequelize. STRING, createdAt: { type: "TIMESTAMP", defaultValue: sequelize.

How do I get the current Unix timestamp?

To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.


2 Answers

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.

like image 178
eggyal Avatar answered Sep 20 '22 02:09

eggyal


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.

like image 35
Adam F Avatar answered Sep 20 '22 02:09

Adam F