Anoop Mundathan
Anoop Mundathan

Reputation: 245

How to change date format in sequelize ORM Query?

I have this model

var Loans = sequelize.define('Loans', {
    book_id: DataTypes.INTEGER,
    patron_id: DataTypes.INTEGER,
    loaned_on: DataTypes.DATE
}

Querying is done like this below.

Loans.findAll().then(function(loans) {
   res.render('book_detail', {loans: loans});
});

My question is, How do I change loaned_on field in just YYYY-MM-DD format in query result, and do not want time stamp.

Currently loaned_on field value displaying as Sun Jan 29 2017 00:00:00 GMT+0000 (GMT) in the html form field and in the db value stored as 2017-01-29 00:00:00.000 +00:00.

Btw, db is sqlite3

Upvotes: 1

Views: 14837

Answers (2)

Tom
Tom

Reputation: 9127

I think a better solution is to use sequelize's custom getters. When you define the model, add a getter for the loaned_on field that does the transformation you want. Like this:

var Loans = sequelize.define('Loans', {
    book_id: DataTypes.INTEGER,
    patron_id: DataTypes.INTEGER,
    loaned_on: {
        type: DataTypes.DATE,
        get: function(fieldName) {
            const rawValue = this.getDataValue('loaned_on');
            // parse raw value using whatever logic you want
            // this won't work, but you get the idea
            return moment(rawValue).toISOString();
        }
    }
}

Also, this SO answer shows how to modify your DB configuration so that dates are stored the way you like (if you're using postgres):

https://stackoverflow.com/a/48388996/814463

There may be an analogous option for sqlite3.

Upvotes: 3

ponury-kostek
ponury-kostek

Reputation: 8060

Use https://momentjs.com/docs/#/parsing/string-format/ or

Loans.findAll().then(function(loans) {
    loans = loans.map(function (loan) {
        loan.loaned_on = loan.loaned_on.getFullYear() + '-' + 
            (loan.loaned_on.getMonth() < 9 ? '0' : '') + 
            (loan.loaned_on.getMonth() + 1) + '-' + loan.loaned_on.getDate();
        return loan;
    });
    res.render('book_detail', {loans: loans});
});

Upvotes: 1

Related Questions