Change Date Formats in AdonisJS

AdonisJS internally uses moment.js and processes all dates in YYYY-MM-DD format. The format, being an international standard, should have been the standard everywhere. Since it is not, let us see how we can modify the date format.

Consider an example - Todo has a end_date field against every record. Your model will look like the below -

const Model = use("Model");
class Todo extends Model {
  /*
  model code
   */
}

module.exports = Todo;

First, inform Adonis that end_date is a valid date field. This is done by using a super that is applicable for all fields. Else, the value will not be serialized as date (not even in the international format).

const Model = use("Model");
class Todo extends Model {
  static get dates() {
    return super.dates.concat(["end_date"]);
  }
}

Next, write methods that will be applicable to the date fields defined in the super.

Do exactly two things-

  • Use a static method called castDates that can return the date in a specified format. Of course it has to return a blank or null value if there is no date value in the first place
  • Use formatDates method to accept dates in specified format

    const Model = use("Model");
    const moment = require("moment");
    class Todo extends Model {
    static get dates() {
    return super.dates.concat(["end_date"]);
    }
    
    static castDates(field, value) {
    if (field == "end_date") return value ? value.format("DD/MM/YYYY") : value;
    else return value ? value.format("DD/MM/YYYY hh:mm a") : value;
    // else used for created_at / updated_at
    }
    
    static formatDates(field, value) {
    if (field == "end_date")
      // format only certain fields
      return moment(value, "DD/MM/YYYY").format("YYYY-MM-DD");
    
    return super.formatDates(field, value);
    }
    }
    
    module.exports = Todo;
    

You can do one or both of the above to format dates in Adonis. A couple of tips -

  1. If you have one locale and a simple web app, you avoid a lot of problems later on by formatting dates in one place as described above
  2. If you are using Adonis as a back-end application and can have multiple types of front-ends, consider returning the date in the international format and formatting dates in the front-end. This will keep data format standardized
  3. If you decide to format dates based on locale, it is recommended to have a locale field against user and format dates based on the user locale. This will provide the scale when you extend your application to multiple locales!
comments powered by Disqus