How to format dates in Adonisjs?

Asked

Viewed 159 times

-2

How can I send DD-MM-YYYY formatted dates to the Adonisjs database?

class AtendimentoSchema extends Schema {
  up () {
    this.create('atendimentos', (table) => {
      table.increments()
      table.date('data_emissao')
      table.timestamps()
    })
  }

  down () {
    this.drop('atendimentos')
  }
}

1 answer

2


You should format the date using Lucid models and not Migration.

For this in the model do the following:

class User extends Model {
  static get dates () {
    return super.dates.concat(['data_emissao'])
  }

  static formatDates (field, value) {
    if (field === 'data_emissao') {
      return value.format('DD-MM-YYYY')
    }
    return super.formatDates(field, value)
  }
}

Just adapt to your model and if you want to know more read the documentation below.

https://adonisjs.com/docs/4.0/lucid#_formatting_date_fields

  • Good morning. Thank you for answering. I made the change in my Service model with the cited code. But it still keeps saving in YYYY-DD-MM format. My return JSON 
{
 "data_emissao": "2020-02-20",
 "created_at": "2020-02-27 10:59:36",
 "updated_at": "2020-02-27 10:59:36",
 "id": 1


  • how vc ta saving in the bank? is using Lucid? the bank that is using accepts in the field the DD-MM-YYYY format ?

  • const call = new Call(); call.data_call = request.input('data_call') await call.save() return call;

  • The formatDates method is called before saving the model instance in the database. Therefore, make sure that the return value is always a valid format for the database engine you are using.

  • is referring to the view? I am using the normal Html5 date input. ')

  • I am referring to the model, as the August said above does not format date in Migration, in the model using the code I mentioned above formats the date, now you have to check if your database accepts the desired format, for example the default of mysql is YYYY-MM-DD and not DD-MM-YYYY

  • I complemented the answer to your field data_emissao be understood by Adonis as a date type field.

  • Everything you’ve been through has been right to work. However I gave rollback and the modifications did not work I deleted the database and I ran Migration:run again and everything is returning with the date formatted in my view. I have no idea what might have happened, but thank you. You’ve helped me a lot. See you

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.