Moment JS in Adonis Framework

#1

Excuse me guys, but you have any resource to integrate moment.js into an Adonis JS project similar to a tutorial, post, etc?

I mean format dates, because I have tried something like this


    let dato = await Student.query()
                              .select('birthday')
                              .fetch()
    let datos = moment(dato).format('YYYY-MM-DD')
    return datos
  }

But it gives me the current date, so I don’t understand how to implement this library

Thanks in advanced

0 Likes

#2

You do not need to install Momoent.js because AdonisJs uses it internally.

In your Student.js model you must inform AdonisJs that ‘birthday’ is a date field in your database table:

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

There is a last step you must ask AdonisJs to do for you by adding castDates() in your Student.js model:

static castDates(field, value) {                                                                                                               
  if (field === 'birthday') {                                                                                                                       
    return value.format('YYYY-MM-DD')                                                                                                          
  }                                                                                                                                            
}

Hope this helps.

Billal Begueradj

2 Likes

Database/Lucid DateTime Problems while saving/reading
#3

it worked very nice thanks, but could you explain me a bit more about this please


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

I still don’t understand this method @begueradj

0 Likes

#4

It is well explained in the documentation:

By default, the timestamps created_at and updated_at are marked as dates.

Define your own fields by concatenating them in a dates getter on your model:

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