spatie/opening-hours

Help: I can't translate the date

JMultimidia opened this issue · 2 comments

Hello, I would like to implement Carbon in this package without the need to use kylekatarnls / business-time.

However, the translation is not working for pt_BR as shown in the image below:

#CODE

use Carbon\Carbon;

$bd = new \JMultimidia\Core\Model();
$now = Carbon::now(new DateTimeZone('America/Fortaleza'));

$ranges = [];

foreach ($horarios as $horario) {
  $ranges[$horario['dia']] =  [
    substr($horario['hora_inicio_01'], 0, 5) . "-" . substr($horario['hora_fim_01'], 0, 5),
    substr($horario['hora_inicio_02'], 0, 5) . "-" . substr($horario['hora_fim_02'], 0, 5),
  ];
}

$range = $openingHours->currentOpenRange($now);
	if ($range) {
	echo "Aberto desde ".$range->start()."\n";
	echo "Vai fechar às ".$range->end()."\n";
	} else {	
	echo "Fechado"."\n";
	//echo "Abre ".$openingHours->nextOpen($now)->format("l H:i")."\n";
	echo "Abre ".$openingHours->nextOpen($now)->formatLocalized("%a %H:%M")."\n";
}

#PRINT
2021-03-20_20-52

Hello, 👋

Firs, of all kylekatarnls/business-time is exactly meant to bridge opening-hours and Carbon.
There is no point in reinventing the wheel.

Second, formatLocalized() uses the locales installed in the OS. So you're not guaranteed to get pt_BR install on every machine you will deploy your code and with the same translations. Prefer using isoFormat() which relies on internal translation files of Carbon which are guaranteed to work consistently on any environment.

Last, nextOpen() (when not using business-time) will return a native DateTime object whatever the object passed in was so you have to re-wrap it with Carbon to get a Carbon object, that's exactly for those reason we provide kylekatarnls/business-time so you don't have to recode and debug all those in your own app code:

Carbon::setLocale('pt_BR');
$now = Carbon::now('America/Fortaleza'); // <-- Timezone can simply be passed as string

$ranges = [];

foreach ($horarios as $horario) {
  $ranges[$horario['dia']] =  [
    substr($horario['hora_inicio_01'], 0, 5) . "-" . substr($horario['hora_fim_01'], 0, 5),
    substr($horario['hora_inicio_02'], 0, 5) . "-" . substr($horario['hora_fim_02'], 0, 5),
  ];
}

$range = $openingHours->currentOpenRange($now);

if ($range) {
  echo "Aberto desde " . $range->start() . "\n";
  echo "Vai fechar às " . $range->end() . "\n";
} else {	
  echo "Fechado\n";
  echo "Abre " . Carbon::instance($openingHours->nextOpen($now))->isoFormat("ddd HH:mm") . "\n";
}

Thank you very much, it worked perfect.
2021-03-21_09-45