Sequelize - use a UNIX timestamp for DATE fields

Is there a way to force Sequelize to use the UNIX timestamp as the default format for both the created At / updatedAt timestamps and the custom Sequelize.DATE fields?

Thanks!

PS I am using MySQL

+4
source share
3 answers

At any given time, there are two possible dates (depending on one position relative to the international date line): that is, conversion from a UNIX timestamp to a date requires consideration of the time zone.

, UNIX 946684800 2000-01-01 00:00:00Z. , . , ?

, (, UTC), ​​- . , , .

, DATE: . .

+6

, , . CreatedAt utils.now sequelize. javascript Date . Squelize , Date, . .

. sequelize. , , unix- - .

+1

eggyal - - MySQL, , unix datetime/timestamp.

I found that a great way to achieve this is to use hooks inside 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 inserts a field createdAtand updatedAtas a timestamp unix.

+1
source

All Articles