簡體   English   中英

Sequelize 和 Postgres 之間的日期格式不正確

[英]Incorrect date format between Sequelize and Postgres

我對 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 結果如下:

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"
  }
]

我的 controller:

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"
  }
]

我找到了解決方案,我需要像這樣使用dialectOptions

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM