Can we always fetch date column as string (varchar) with knex and postgres?

元气小坏坏 提交于 2019-12-05 20:51:04

node-postgres driver is the part which actually creates Date() objects from data sent from date columns (https://node-postgres.com/features/types#date-timestamp-timestamptz)

With postgres you can modify node-pg's type parsers like described in here https://github.com/brianc/node-pg-types

Date types type's oid which is 1082 can be fetched with following query

select typname, oid, typarray from pg_type where typname = 'date' order by oid;

So to to override date type to be passed as string it is enough to do this before setting up your db connection (I suppose one could do that for example in knexfile.js):

var types = require('pg').types;
// override parsing date column to Date()
types.setTypeParser(1082, val => val); 

Setting the typeParser for pg is probably the better answer, but you can also use Bookshelf's Processor Plugin to change what that particular date attribute looks like:

bookshelf.plugin('processor')
var MyModel = bookshelf.Model.extend({
  tableName: 'stuff',
  processors: {
    date: function(value) {
      /* you can use any other method for getting the date part */
      return value.toLocaleDateString()
    }
  }
})

To me it didn't work the most voted solution. What it worked to me was this, using momentjs.

    import * as moment from 'moment';
    types.setTypeParser(1114, str => moment.utc(str).format());
    return knex({
        client: 'pg',
        connection: {
          host : 'localhost',
          user : 'postgres',
          password : '',
          database : 'localDB',
        }
    })

Credits to Oleksii Rudenko https://60devs.com/working-with-postgresql-timestamp-without-timezone-in-node.html

In order to get the time as per the local time zone in a string format, we can use.

  var date =function(value) {
      /* you can use any other method for getting the date part */
        return value.toLocaleDateString()
  }

date('1990-12-30T18:30:00.000Z'); date(value)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!