How to pass a DateTime from NodeJS Sequelize to MSSQL

后端 未结 3 1203
走了就别回头了
走了就别回头了 2021-02-07 09:32

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 char

相关标签:
3条回答
  • 2021-02-07 09:34

    You can use this variable:

    const timestamps = new Date() + 3600 * 1000 * 7;
    
    0 讨论(0)
  • 2021-02-07 09:48

    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');
    };
    
    0 讨论(0)
  • 2021-02-07 09:55

    I figured this out, without changing the data type in the SQL database.

    In my Model, I had my column defined as DataTypes.DATE, which, according to the Sequelize documentation, is the equivalent of a DateTime in SQL. However, this was throwing the error. When I changed the definition to DataTypes.STRING, and then added this:

    var normalizedDate = new Date(Date.now()).toISOString();
    

    normalizedDate now passes through to the DateTime column in SQL without a problem. The issue that I can tell, is Sequelize was adding a time zone to the Date before passing it. Such as, a date like:

    '2017-11-01 16:00:49.349'
    

    was being passed through as:

    '2017-11-01 16:00:49.349 +00:00'
    

    and it looks like SQL server does not like the '+00:00'.

    I hope this helps others.

    0 讨论(0)
提交回复
热议问题