Sequelize — 对 DATE 字段使用 UNIX 时间戳

2022-01-19 00:00:00 node.js mysql sequelize.js

有没有办法强制 Sequelize 使用 UNIX 时间戳作为默认时间格式both 用于 createdAt/updatedAt 时间戳和 用于自定义 Sequelize.DATE 字段类型?p>

谢谢!

附:我正在使用 MySQL

解决方案

在任何给定的时间,有两个可能的日期(取决于一个人相对于国际日期变更线的位置):即从 UNIX 时间戳转换到某个日期需要考虑时区.

例如,UNIX 时间戳 9466848002000-01-01 00:00:00Z.虽然这代表了大西洋以东几乎所有地方新千年的第一天,但​​大西洋以西的任何地方仍然是千年前夕.那么它代表哪个日期呢?

虽然可能将日期转换为时间戳,但必须定义自己的惯例(例如,将给定日期表示为 UTC 中的午夜),否则可能会表示相同的日期不同的编码.一般来说,这是一个坏主意,可能会产生各种意想不到的后果.

DATE 数据类型存在是有原因的:它是正确的 存储日期的方法.使用它.

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

解决方案

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.

相关文章