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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With