1

I would like to output a formatted period of time for different locales, e.g.: de_DE: 25. - 28. August 2022 es_ES: 25-28 de agosto de 2022

So far I have to 'construct' this output. Example:

$locales = array(
    'de_DE',
    'en_GB',
    'fr_FR',
    'es_ES',
    'zh_CN',
    'ru_RU',
);
$date = new \DateTime('2022-08-25');
$date2 =new \DateTime('2022-08-28');
foreach ($locales as $loc){
$fmt = new IntlDateFormatter(
$loc,
IntlDateFormatter::LONG,
IntlDateFormatter::NONE,
'Europe/Berlin',
IntlDateFormatter::GREGORIAN);
    if ($loc == 'zh_CN')
    {
      $fmt->setPattern('y年M月d-');
      $part1= $fmt->format($date);
      $fmt->setPattern('d日'); 
      $part2= $fmt->format($date2);
      echo $loc.' formatierte Ausgabe:  ' .$part1.''.$part2.'| some text<br>';
    }
....

Output: 2022年8月25-28日| some text

I'm sure there must be a better way to do this? Thanks in advance!

schasiepen
  • 11
  • 1
  • You can move the formatting to the configuration area itself: https://3v4l.org/6NQAd – Chris Haas Jun 20 '22 at 15:02
  • Thanks, that looks much neater! But shouldn't there be a simpler solution? – schasiepen Jun 20 '22 at 17:39
  • Simplicity is subjective, generally. You could abstract this away further to a config system. For instance, this could be stored in a YAML file somewhere, or you could use a database. But in reality, you are taking well-defined objects (dates) and converting them to strings and applying a locale's language specifics to them, along with some arbitrary text. Although PHP has a class for date ranges (`DatePeriod`) it isn't intended for this situation and I don't know of any built-in way to (easily) use it for formatting. – Chris Haas Jun 20 '22 at 18:07
  • You could use https://github.com/flack/ranger for this – jspit Jun 21 '22 at 13:09

0 Answers0