0

I need to send to database a date format like: DD-MM-YYYY. Or some way to format in frontend using Edge template

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

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

I've tried

class Atendimento extends Model {



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


}

** JSON output**

{
  "data_emissao": "2020-02-14",
  "id": 2
}

Ramon
  • 39
  • 2
  • 10

3 Answers3

2

format accept default only create_at and update_at columns if you format another column then you use get dates like this

static get dates () {
    return super.dates.concat(['column_name'])
  }

in you case column name is data_emissao

Example :-

class Atendimento 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)
   }


}

for more detail check adonis.js official doc

Amit Kadivar
  • 798
  • 4
  • 12
1

In 2021 (adonis-ts-app version 4) use @column.date() decorator in your model:

@column.date()
public data_emissao: DateTime

see the reference: ORM: Decorators

Then you can use luxons toFormat() to convert to a String:

data_emissao.toFormat('yyyy')
bjelli
  • 9,752
  • 4
  • 35
  • 50
-1

If you're able to use external packages try moment js, it will help you with that

JVictorV
  • 82
  • 1
  • 6