How to use .format in Adonisjs

Hi , According to

I add this in Models

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

And this

static formatDates (field, value) {
    if (field === 'gstrp '|| field == 'crtd_date') {
      return value.format('YYYY-MM-DD')
    return super.formatDates(field, value)

the error said vaule.format is not function

I console.log (value)

I got this 2019-03-29T09:27:35.699Z

then I check in my database It show only 2019-03-29 (date type)

How to deal with this and How to add multiple field in static get dates

Thanks for help

1 Like

I think date formatting goes in the model not the controller.


I’m adding this in model . It’s still get error s

You got that error because you forgot to add gstrp to dates array, which thing you can do this way:

static get dates () {
  return super
    .concat(['crtd_date', 'gstrp'])

I had the same error a while ago, and I did have the fields in dates array.

My solution was to import moment.js in the model.

const moment = require("moment");

Now, Change return value.format('YYYY-MM-DD') to -

return moment(value, "DD/MM/YYYY").format("YYYY-MM-DD");

‘DD/MM/YYYY’ is my input format - your format may differ.

The default ‘format’ solution is definitely lighter (& probably faster), but I was stuck and had to find a way out :slight_smile:

No, you do not need to require Moment.js as it is used internally by AdonisJs. @prashanth1k

Hi @begueradj,

I got vaule.format is not function error too, even for the default created_at field.

I wrote something like in my Model

static formatDates(field, value) {
console.log(field); //shows created_at
console.log(value instanceof Date); //shows true
console.log(value.format(‘YYYY-MM-DD HH:mm:ss’)); //shows value.format is not a function

besides formatDates function nothing is defined in my Model. Maybe I am missing something?

Here is an example on how to use format(): How to use Moment.js with AdonisJs @Patrick-Shih


@begueradj thanks you very much and I think I got where the issue is.

By reading the source code I found the document shown in about formatDates is wrong.

Here is the snippet of Model source code

static formatDates (key, value) { 
  return moment(value).format(DATE_FORMAT)
static castDates (key, value) {
  return value.format(DATE_FORMAT)

The value in castDates is actually a Moment object while the value in formatDates are not. By my test it could be javascript Date object or even string and therefore it has no format function which is belong to Moment object.

I think the workaround to use format in formatDates is like @prashanth1k says. Hopefully this helps :slight_smile:

1 Like