This page looks best with JavaScript enabled

Change Date Formats in AdonisJS

 ·   ·  ☕ 3 min read

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 -

1
2
3
4
5
6
7
8
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).

1
2
3
4
5
6
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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!
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things