什么是使用'sequelize.fn`方法来格式化sqlite3 dateTime的正确方法



我使用mySQL和sqlite3数据库并在控制台中以JSON格式显示数据。使用MySQL,Sequelize.fn函数使我能够控制createdAtupdatedAt字段的格式:

[Sequelize.fn('date_format', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']

例如:

Article.findAll({
    attributes: [
        'id',
        'title',
        'body',
        [Sequelize.fn('date_format', Sequelize.col('createdAt'), '%m-%d-%Y %H:%i:%s'), 'createdAt'],
        [Sequelize.fn('date_format', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']
    ]
})
    .then(tasks => {
        console.log(JSON.stringify(tasks, null, 2))
    })

返回以下内容:

  {
    "id": 27,
    "title": "This is a test title",
    "body": "The main body of the article appears here.",
    "createdAt": "05-28-2017 23:41:42",
    "updatedAt": "05-28-2017 23:41:42"
  }
但是,

sqlite不识别date_format功能并引发错误:

Unhandled rejection SequelizeDatabaseError: SQLITE_ERROR: no such function: date_format

研究表明,正确的SQLITE函数为strftime,但是尽管出现了错误消息,但输出为null。例如,

[Sequelize.fn('strftime', Sequelize.col('updatedAt'), '%m-%d-%Y %H:%i:%s'), 'updatedAt']

导致

{
  "id": 42,
  "title": "Hello world!",
  "body": "This is stored in SQLite!",
  "createdAt": "2017-05-28T23:19:41.738Z",
  "updatedAt": null
}

有人可以指向正确的方向吗?

我也有同样的问题。你快到了。只有续集的参数为错误的顺序。

[Sequelize.fn('strftime', '%m-%d-%Y %H:%i:%s', Sequelize.col('updatedAt')), 'updatedAt']

您的日期应适当格式化。

感谢您将我指向正确的方向!

最新更新