Reputation: 1022
I have used Sequelize to state the type of one of my columns as follows:
userTime: DataTypes.TIME
This declares the column in MS SQL as time(7)
format.
I add data to the respective column as a string. e.g: "12:00"
However, when I retrieve the data from the DB it comes out in the following format:
userTime: "1970-01-01T12:00:00.000Z"
How can I change the output to be of the following format, using Sequelize:
userTime: "12:00"
Is there a possibility, to use FORMAT of the return type in Sequelize?
Upvotes: 1
Views: 1668
Reputation: 1022
Actually, I solved the problem, was way easier than I thought.
userTime: {
type: DataTypes.TIME,
allowNull: true,
get() {
const userTime = this.getDataValue('userTime');
if(userTime == null) return userTime;
const time = new Date(userTime);
let hours = addZero(time.getUTCHours());
let minutes = addZero(time.getUTCMinutes());
let combinedTime = hours + ":" + minutes;
return combinedTime;
}
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Upvotes: 0
Reputation: 58563
What I would suggest is to create a getterMethods
, work like a virtual field
, that you will get in each query.
var User = sequelize.define('users',{
userTime:{
type: DataTypes.TIME
},
name:{
type: db.Sequelize.STRING,
allowNull: false
},
image: {
type: db.Sequelize.STRING,
allowNull: true
},
.... // other fields
},{
getterMethods:{
modifiedUserTime() {
return moment(this.userTime); // modify the time as you want
}
}
});
Upvotes: 2