如何将 NodeJS Sequelize 中的 DateTime 传递给 MSSQL

我有一个 NodeJS 项目,我正在尝试使用 Sequelize 传递一个UpdateDate"字段.我收到错误从字符串转换日期和/或时间时转换失败".我尝试过传递一些不同的东西:

I have a NodeJS project, and I am trying to pass an 'UpdateDate' field using Sequelize. I am receiving the error 'Conversion failed when converting date and/or time from character string'. I have tried passing a few different things:

Date.now()
new Date().toISOString()

都不行.我错过了一些简单的东西吗?我无法更改表上的列定义.据我所知,将诸如 '2016-05-23 10:39:21.000' 之类的字符串传递给 SQL DateTime 字段在 SSMS 中有效,但在使用 Sequelize 和 Node.js 时似乎是一个问题.

Neither work. Am I missing something simple? I cannot change the column definition on the table. As far as I know, passing a string such as '2016-05-23 10:39:21.000' to a SQL DateTime field works in SSMS, but it seems to be an issue when using Sequelize and Node.

谢谢

扎克

推荐答案

这是由 已知的Sequelize 中的问题.解决方案是将 Sequelize 的日期修补为字符串格式实现,如 在此处解释,以便正确处理所有日期.下面是修复错误的代码.

This is caused by a known issue in Sequelize. The solution is to patch Sequelize's date to string format implementation, like explained here, so that all dates are handled properly. Below is the code that fixes the error.

const Sequelize = require('sequelize');

// Override timezone formatting for MSSQL
Sequelize.DATE.prototype._stringify = function _stringify(date, options) {
  return this._applyTimezone(date, options).format('YYYY-MM-DD HH:mm:ss.SSS');
};

相关文章