Chain method to toDate()

I need to write a custom method to chain after toDate() that takes into account the actual, selected language.

What kind of method should I write, a field method ?


toDate() returns a string or integer, not a field, so you cannot chain any other field method.

Why not use a custom date field method that returns the required value? Or what do you want to achieve? Format the date according to locale? In the latter case, a language dependent format set in config would make more sense.


Well, I am using intl (in config). For Spanish and Catalan it outputs month names lowercase (which is correct), but a client is adamant on that they need capitalized month names.

So I need to modify the output of toDate() because there is, as far as I understand, that the formatting happens.

Example of output: 11 de febr.
Desired output: 11 de Febr.

I was just going to do some string replacement work, perhaps using fixed arrays for abbreviated month names, or regex, etc.



Getting back to you on this.

I have two separate issues:

  1. I need a different date format depending on the actual language. In the past you have suggested that, if I need different ->toDate() formats, depending on the actual language, I could use a language variable that would store the format, so I assume something like: ->toDate(t('dateFormat')) …do you still recommend this ?

  2. Additionally, as described in the above post, I need to capitalize specific words from toDate()'s output. For example from 11 de febr. to 11 de Febr. You said perhaps I should use a ‘language dependent format set in config’, would that solve the problem I just described? and how to set that?


Yes, absolutely.

The easiest would probably be some string replacement using a regex pattern.

I read through the ICU date formatting stuff to find if there is a way to modify the output via some custom settings, but didn’t quite understand it.

1 Like

Thank you

And regarding the topic title: You cannot chain another method onto toDate() because toDate() returns either a string, an integer or null and not a field object.

1 Like

Maybe this plugin is helpful for your task:

1 Like

What you can do if the patterns don’t work is to separate the stuff:

$date = $page->date();
$dateString = '%s de %s %s';
echo sprintf($dateString, $date->toDate('d') , ucfirst($date->toDate('MMM')), $date->toDate('Y'));

Wrap this in a new field method.

Yes! you already mentioned that above

And, the field method seems like a good alternative too, I’ll wrap my head around the approaches, and report back what was best.