I have borrowed beautiful Cokidoo DateTime class, that converts regular DateTime to “ago format”.
I’m developing multilingual web-site and wanted to replace year ago, years ago, month ago with variables.
Code example:
protected $strings = array(
'y' => array('1 year ago', '%d years ago'),
'm' => array('1 month ago', '%d months ago'),
'd' => array('1 day ago', '%d days ago'),
'h' => array('1 hour ago', '%d hours ago'),
'i' => array('1 minute ago', '%d minutes ago'),
's' => array('now', '%d secons ago'),
);
Is this possible to do this without using replace methods?
Obviously this didn’t work:
'm' => array('1' . $month_ago, '%d' . $months_ago),
Any help please?
That class would be much more useful if it did not extend
DateTime. The only thing it does is format a date, it has no reason at all to be a date. It could just as easily create aDateTimeon demand and work on that instead of$this.If you make this modification (and appropriately rename the class to e.g.
DateTimeDiffFormatter) then suddenly all the possibilities are open: you can pass a parameter to the constructor that determines the language to be used, or even better pass in some reference to your i18n component. Then for example you could haveand
Finally, it’s a really bad idea to assume that you can hardcode the format of the localized strings to “X minutes ago” and similar. The number needs to be part of the format string since in many cultures it does not precede the “how long ago” part.
Update
I adapted Ilia’s candidate solution to bring it in line with the suggestions above; the result is here.