Reputation: 302
I have the following entity in my Symfony 4 project
class Post
{
/**
* @var string
*
* @ORM\Column(name="date_string", type="string", length=11)
*/
private $dateString;
public funtion getDateString()
{
return $this->dateString;
}
}
I know, I could use \DateTime for that, but it does not matter for my case ;)
What I want is, to convert the date string depending on the localization of the user. Therefore I created a new translation and used the key "dateFormat" to set the date format for each localization.
messages.en.yaml
dateFormat: "m/d/Y"
messages.de.yaml
dateFormat: "d.m.Y"
My question is: What is the best practice to get the formatted date string? I have written a repository method, but I do not like this solution. When I am accessing the method, I always have to fetch the repository and its not comfortable to use it in Twig templates.
PostRepository:
public function getFormattedDateString(Post $post): string
{
$dateTime = new \DateTime($post->getDateString());
$dateFormat = $this->translator->trans('dateFormat');
return $dateTime->format($dateFormat);
}
Rather I would like to use the method directly out of the entity. Something like this:
$post->getFormattedDate();
But this won't work, because I need to inject the TranslatorInterface into the Entity. This sucks. Or is there a way to modify the result of the getDateString() method? (annotations?)
How would you solve the task? Thanks a lot
Upvotes: 0
Views: 2317
Reputation: 78
Maybe you could create a service that would expose a function, which will take your User as a parameter. It would resolve the date string you need.
For example, you could create a DateFormatResolverInterface
, that would implement a resolveFormat(User $user)
. Then, create a RequestLocaleDateFormatResolver
class that implements the interface, and resolve the format inside the resolveFormat()
function. You can always change the way you resolve the format by creating a new class
that implements the interface
.
Then, use this whenever you need : $this->get('acme.date_format_resolver')->resolveFormat($user);
OR
$this->get(DateFormatResolverInterface::class)->resolveFormat($user);
Hope this helps.
Upvotes: 0
Reputation: 8162
I assume you don't want to use the IntlDateFormatter
and want to re-invent a way to translate a date.
I would do a service LocaleDateFormatter
than you can use when you need to translate a date to a locale formatted Date (and a twig filter to use it on twig template)
__construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function getFormattedDateString($dateString): string
{
$dateTime = new \DateTime(dateString);
$dateFormat = $this->translator->trans('dateFormat');
return $dateTime->format($dateFormat);
}
Upvotes: 2