How should the data be sent for datatype TIME in Sequelize/ Node JS

Viewed 12163

I have a time column in my mssql db. I want to post data through an API to this table, but this field throws the error - "Conversion failed when converting date and/or time from character string". I am sending the time field as a string like "13:00". When getting the data from db through sequelize, I get as an ISOString like "1970-01-01T08:00:00.000Z", but the data on the db is like "13:00:00"(hh:mm:ss). I tried sending "13:00:00" and "1970-01-01T08:00:00.000Z", both do not seem to work.

1 Answers

I created a simple nodejs app with sequelize and was able to insert both 13:00 and 13:00:00 for Time Datatype successfully.

I have checked with both Time and Date datatypes. I got this error Conversion failed when converting date and/or time from character string only when I tried to insert 13:00 into Date datatype. So check the datatype of your column and make sure it is Time and not Date

Kindly refer this code and check where you have gone wrong.

var http = require('http');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('DBName', 'UserName', 'Password', {
  host: 'localhost',  
  port:12672,
  dialect: 'mssql',
  options:{
    encrypt:false,
    instancename: 'SQLEXPRESS'
  }
});



const User2 = sequelize.define('user2', {
  name: {
    type: Sequelize.STRING
  },
  DateTimeCol: {
    type: Sequelize.DATE
  },
  TimeCol: {
    type: Sequelize.TIME
  }
});

User2.sync().then(() => {
   User2.create({
    name: 'Rahul',
    DateTimeCol: '2018-01-01T08:00:00.000Z',
    TimeCol: '13:00'
  });
  User2.findAll().then(data => console.log(data));
});


var server = http.createServer(function(req, res) {
res.writeHead(200);
res.end();
});
server.listen(8080);
Related