Junaid
Junaid

Reputation: 488

Sequelize store date part only in (mysql) table

My application wants to store only date part in one of tables. In Sequelize there is only one data type, Sequelize.DATE, that can be used. On MySQL table it creates DATETIME column.

How can I have a column in database table to store only date, without time. part? MySQL is having separate DATE and DATETIME datatypes, but could not find a way to tell that in Sequelize.

Or can we make to ignore time part while running queries using Date object? (I know we can use getters and setters with properties. No idea whether it will work while running queries having conditions for the date field.)

Upvotes: 5

Views: 11194

Answers (2)

PRS
PRS

Reputation: 702

Something of note... DATEONLY type in Sequelize v3 is NOT working as would be expected. It returns a Datetime with timezone, so if you are doing date comparisons they will not work as you expect unless your server timezone GMT. In my case, I'm working with holidays across timezones, so this was a headache for me. They do have a fix as of 2016-11-01 on the master branch, but it has not made it's way into v3 and there is no v4 yet. To work around the issue for now, you can do this in your model definition, which I found on that same link:

regDate: {
  type: DataTypes.DATEONLY,
  get: function() {
    return moment.utc(this.getDataValue('regDate')).format('YYYY-MM-DD');
  }
}

Upvotes: 5

Diosney
Diosney

Reputation: 10580

As of sequelize ^3.7.1 it does have support for a DATEONLY data type.

See http://docs.sequelizejs.com/en/latest/api/datatypes/ and https://github.com/sequelize/sequelize/blob/f678009d7514b81a6f87e12b86360e9a597e3ca8/lib/data-types.js#L357

for the implementations.

Upvotes: 6

Related Questions