Same date with more than one format

Most of my date fields must be shown in different formats. When filling a date type form field I need to get the value in ‘YYYY-MM-dd’ format, which is working fine, but when showing information, I’d rather use a more readeable format (in Brazil it’d be like ‘dd/MM/YYYY’), but I don’t know how to use more than one formatt for the same field.

I read the docs and some posts about it but I’m sure I’m missing something. I’d love some help.

Thanks in advance!

Hi @lucasdoamaral

You could apply the modifier on the model with this:

static castDates (field, value) {
    if (field === 'created_at') {
      return `${value.format('MMMM DD, YYYY')}`
    }

    if (field === 'updated_at') {
      return `${value.fromNow(true)} ago`
    }

    return super.formatDates(field, value)
  }

I used the created_at and updated_at columns as an example to show that you could target any given field.

I hope this helps you.

3 Likes

Hey, @adegbengaagoro! Thanks for your reply!

The problem is I need the same field, let’s say “created_at” to be shown in both formats ‘YYYY-MM-DD’ and ‘DD/MM/YYYY’ deppending the occasion.

Hi @lucasdoamaral

You’re welcome. In that context, maybe you should consider using Moment.js within your controllers, so for each scenario you want the date presentation changed, you can just use Moment.js to handle that.

This is a great, short and quick reference to help you with it.

Cheers

1 Like

Thanks for the link, @adegbengaagoro!

I’m looking for a solution that can be put in the model, I think. In all aproachs found until now I’d have to do this in the controller everytime I need different formats and that’s what I’m trying to avoid, speccially because the data it’s in an array.

Depending on your use case, you could do -

static castDates(field, value) {
  if (field == 'created_at') {
    if (somecondition) 
      return value ? value.format("DD/MM/YYYY") : value;
    else 
      return value ? value.format("MM/DD/YYYY") : value;
  }  
}

Alternatively, you could use computed fields? You are trying to retrieve different formats from same field depending on other variables - a computed date field can reflect the original date field in a different format depending on another value.