【问题标题】:Incorrect date format between Sequelize and PostgresSequelize 和 Postgres 之间的日期格式不正确
【发布时间】:2022-02-16 16:37:23
【问题描述】:

我对 postgre 结果和 Sequelize 预期结果有疑问。相同的查询,但 Sequelize 和 Postgre 之间的结果不同,我认为是关于 timezome 的。我的时区是Europe/Paris

我的查询用于检索本周的所有总价格:

SELECT date_trunc('day', "date") AS "date_alias", sum("cost") AS "total"
FROM "finance" AS "Finance" 
WHERE "Finance"."date" 
BETWEEN '2022-02-13 23:00:00.000 +00:00' AND '2022-02-19 23:00:00.000 +00:00' 
GROUP BY "date_alias"

Postgre 结果如下:

周数据如下:

Sequelize 返回的结果:

Executing (default): SELECT date_trunc('day', "date") AS "date_alias", sum("cost") AS "total" FROM "finance" AS "Finance" WHERE "Finance"."date" BETWEEN '2022-02-13 23:00:00.000 +00:00' AND '2022-02-19 23:00:00.000 +00:00' GROUP BY "date_alias";
[
  Finance {
    dataValues: { date_alias: 2022-02-14T00:00:00.000Z, total: '76' },
    _previousDataValues: { date_alias: 2022-02-14T00:00:00.000Z, total: '76' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Finance {
    dataValues: { date_alias: 2022-02-17T00:00:00.000Z, total: '14' },
    _previousDataValues: { date_alias: 2022-02-17T00:00:00.000Z, total: '14' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Finance {
    dataValues: { date_alias: 2022-02-18T00:00:00.000Z, total: '10' },
    _previousDataValues: { date_alias: 2022-02-18T00:00:00.000Z, total: '10' },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]

在 JSON 中:

[
  {
    "date_alias": "2022-02-13T00:00:00.000Z",
    "total": "10"
  },
  {
    "date_alias": "2022-02-14T00:00:00.000Z",
    "total": "76"
  },
  {
    "date_alias": "2022-02-17T00:00:00.000Z",
    "total": "14"
  },
  {
    "date_alias": "2022-02-18T00:00:00.000Z",
    "total": "10"
  }
]

我的控制器:

const { Op, Sequelize } = require('sequelize')
const {startOfWeek, lastDayOfWeek, startOfMonth, lastDayOfMonth, lastDayOfYear, startOfYear } = require('date-fns');

module.exports = {
    async getAll(req, res) {
      try {
        
        //default week
        let startedDate = startOfWeek(new Date(), { weekStartsOn: 1 });
        let endDate     = lastDayOfWeek(new Date(), { weekStartsOn: 1 });
        let periodParam = 'day';

        if(req.params.period && req.params.period === "month") {
          startedDate = startOfMonth(new Date());
          endDate     = lastDayOfMonth(new Date());
          periodParam = 'month';
        }
        if(req.params.period && req.params.period === "year") {
          startedDate = startOfYear(new Date());
          endDate     = lastDayOfYear(new Date());
          periodParam = 'year';
        }

        let options = {
          ...(req.params.period && { attributes: [
            [ Sequelize.fn('date_trunc', periodParam, Sequelize.col('date')), `date_alias`],
            [ Sequelize.fn('sum', Sequelize.col('cost')), 'total']
          ]}),
          ...(req.params.period &&  {group: ['date_alias']}),
          where: {
            date: {
              [Op.between] : [startedDate, endDate],
              //[Op.gte]: startedDate,
              //[Op.lt]: endDate,
            }
          },
          ...(!req.params.period && {order: [
            ['date', 'ASC']
          ]}),
          ...(!req.params.period && {include: {
              association: 'taxonomies',
              attributes: ['id'],
              through: {
                attributes: []
              }    
            }
          }),
        };

        const data = await req.Model.findAll(options);
        res.json(data);
      } catch (err) {
        res.status(500).send(err);
      }
    },
}

为什么 Sequelize 返回 2022-02-13T00:00:00.000Z 而不是 2022-02-13T23:00:00.000Z ? 我的预期结果应该是:

[
  {
    "date_alias": "2022-02-13T23:00:00.000Z",
    "total": "43"
  },
  {
    "date_alias": "2022-02-14T23:00:00.000Z",
    "total": "43"
  },
  {
    "date_alias": "2022-02-17T23:00:00.000Z",
    "total": "14"
  },
  {
    "date_alias": "2022-02-18T023:00:00.000Z",
    "total": "10"
  }
]

【问题讨论】:

    标签: javascript node.js date timezone sequelize.js


    【解决方案1】:

    我找到了解决办法,我需要像这样用dialectOptions配置sequelize

    const {Sequelize} = require('sequelize');
    
    const sequelize = new Sequelize(process.env.PG_URL, {
        logging: true,
        dialectOptions: {
            useUTC: false, //for reading from database
            dateStrings: true,
            typeCast: function (field, next) { // for reading from database
              if (field.type === 'DATETIME') {
                return field.string()
              }
                return next()
              },
          },
        timezone: 'Europe/Paris',
    });
    
    module.exports = sequelize;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多