javascript - knex.js 迁移中的时间戳字段

标签 javascript node.js sqlite datetime knex.js

我目前正在使用 knex 为我的数据库 (sqlite3) 编写迁移。我正在制作“用户”表,我希望有两个时间戳字段,created_atupdated_at。我希望它们不可为空,并在向表中插入一行时默认添加。我可以使用类似 table.timestamp("created_at).notNullable().defaultTo(knex.fn.now()) 但在 SQLiteStudio 中它显示为格式化时间戳 YYYY-MM-DD HH:MM :UTC 时区的 SS(所以不是我的时区)。所以我有 2 个问题:

  1. 如何将此日期设置为我的时区?
  2. 是否可以在 sqlite 中以这种方式设置日期时间字段,当我从 SELECT 语句中获取它时,它作为 Unix 时间戳(整数)返回,并且仍然在 SQLiteStudio 中显示为格式化日期?

这是我的迁移代码:

exports.up = function(knex, Promise) {
return Promise.all([
    knex.schema.createTable('users', function(table) {
        table.increments("_id").primary().notNullable();
        table.text("login").unique().notNullable();
        table.text("given_name").notNullable();
        table.text("family_name").notNullable();
        table.timestamp("created_at").notNullable().defaultTo(knex.fn.now());
        table.timestamp("updated_at").notNullable().defaultTo(knex.fn.now());
        table.boolean("is_active").notNullable().defaultTo(true);
    }),
]);
};

最佳答案

寻找 here应该给一些线索。

Date And Time Functions

SQLite supports five date and time functions as follows:

date(timestring, modifier, modifier, ...) 
time(timestring, modifier, modifier, ...) 
datetime(timestring, modifier, modifier, ...)
julianday(timestring, modifier, modifier, ...) 
strftime(format, timestring, modifier, modifier, ...)

我相信这个想法是始终将时间存储为 UTC,然后转换为本地时间,当您想要显示该值时使用 strftime()

给出了一个使用 localtime 标志和 datetime 的例子:

Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.

SELECT datetime(1092941466, 'unixepoch', 'localtime');

对于人类可读的文本,您需要 strftime()。这有点粗糙,但它有效。我希望 knex 可以进行此类查询,我什至从未听说过!

关于javascript - knex.js 迁移中的时间戳字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152833/

相关文章:

node.js - 出于测试目的重放 RPC 调用

iphone - iOS - 1000 的文字字符串,如何处理?

javascript - 带有 AngularJS 和 customVariables 的 BrainTree.js

javascript - 使用 ng-repeat 在每次重复中调用函数

javascript:根据特定日期获取星期几

javascript - 如何录制 RTSP 流

php - [PHP/JavaScript] : Get PHP session value in other file's JavaScript function

node.js - 使用带有 1 :M associations 的 Sequelize

android - 在使用 Kotlin 为 SQLite 中的列指定类型时,如何使用一组特定的词?

java - 无法在内存中的 sqlite 数据库上创建表,没有任何错误消息