使用 knex.fn.now() 自动添加日期的 knex 和时区

问题描述

我在 express 中使用 knex.js。 当我插入或更新一些记录时,我遇到了一个问题,我得到了服务器的时间戳,而不是我使用以下指令在 express 中设置的时间戳。

process.env.TZ = 'Asia/Karachi';

虽然只要我现在在 express 中使用上述方法就可以正常工作,但是当我插入一条记录时,时区是服务器的而不是我指定的时区,所以我用谷歌搜索并找到了几种解决方案。 以下是我的迁移之一:

import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void> {
    return knex.schema.createTable('companies',function(table: Knex.TableBuilder) {
        table.bigIncrements().primary();
        table.string('name',255).notNullable();
        table.text('address').notNullable();
        table.string('slug').notNullable();
        table.string('mobile').notNullable();
        table.enu('status',[ 'enable','disable' ]).notNullable().defaultTo('enable');
        table.enu('type',[ 'sole','distribution','both' ]).notNullable();
        table.timestamp('created_at').defaultTo(knex.fn.now());
        table.timestamp('last_updated_at').defaultTo(knex.fn.now());
    });
}

export async function down(knex: Knex): Promise<void> {
    return knex.schema.dropTableIfExists('companies');
}

如您所见,我在创建迁移时添加了 knex.fn.now 作为默认时间。

作为解决方案,我尝试了以下方法,但它们对我不起作用:

module.exports = {
    development: {
        client: CLIENT,connection: {
            database: DATABASE,user: PG_USER,password: PASSWORD,host: HOST,timezone: '+05:00'
        },migrations: {
            tableName: 'knex_migrations'
        }
    },staging: {
        client: CLIENT,pool: {
            min: 2,max: 10
        },production: {
        client: CLIENT,migrations: {
            tableName: 'knex_migrations'
        }
    }
};

我也尝试在生产连接下设置为以下也不起作用。

时区:“亚洲/卡拉奇”

我也尝试在生产池中添加 afterCreate 方法,但也没有奏效。

pool: {
    afterCreate: function(connection,callback) {
      connection.query('SET time_zone = Asia/Karachi;',function(err) {
        callback(err,connection);
      });
    }
 }

当我添加一条记录时,我没有为时间戳分配日期,所以我在 2021-01-22T02:53:53.000Z 创建的时间是早上 12:am。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)