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 -
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).
Next, write methods that will be applicable to the date fields defined in the
Do exactly two things-
- Use a static method called
castDatesthat 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
formatDatesmethod to accept dates in specified format
You can do one or both of the above to format dates in Adonis. A couple of tips -
- 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
- 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
- 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!