Default castDate to UNIX timestamp


Is it possible to change default cast dates logic? Or only way is to write a trait for Lucid and assign that trait to all models?

Idea is to ALWAYS send all dates as UNIX timestamp to client. What is the best approach for this?

@virk: suggestion: what about adding config values for this to config/database and inside lucid/src/Lucid/Model/Base pull that config as DATE_FORMAT and CAST_DATE_FORMAT with default value of ‘YYYY-MM-DD HH:mm:ss’?


How about this…

In this example it shows how to cast dates to whatever format

You can combine this with your own base model class which extends AdonisJs model.


class BaseModel extends Model {
  static castDates (field, value) {
    // convert to unix timestamp

class User extends BaseModel {}


I know about this.

I already wrote model trait to handle this problems.
But I don’t want to add this trait or additional logic to all models. I want this to be default for any newly created model.

If anyone is interested in trait for date casting… Here it is:


class CastDate {
  register(Model, customOptions = {}) {
    const defaultOptions = {
      format: 'x' // milliseconds (unix timestamp)

    const options = Object.assign(defaultOptions, customOptions)

    Model.castDates = function (field, value) {
      return value.format(options.format)


module.exports = CastDate

To use it… Just add a trait to your model:
Or if you want some other format for all dates, call it like this:
this.addTrait('CastDate', {format: 'DD.MM.YYYY.'})

It accepts any format from:


This is awesome!


@romain.lanz accepted this as soultion but I’m still searching for a better way :slight_smile:

If anyone have any idea how to change default adonisjs date format to unix without any traits or similar I would really appreciate it …

I belive the only way is to add this possibility to lucid database config. So lucid/src/Lucid/Model/Base.js would read format from Config.get(‘database.castDateFormat’, ‘YYYY-MM-DD HH:mm:ss’) or something…