I am using bootstrap-material-datetimepicker
on my Symfony form so the user can select his birthday.
The datetimepicker
returns a string for example "Saturday 16 May 2020"
.
I want to calculate the age
of the user (int number) from that string birthday!
How can I calculate the age? Is there a way to make the datetime return date or int instead of the string ?
The code of my form :
{% extends 'base.html.twig' %}
{% block body %}
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
<div class="form-line">
{{ form_widget(form.birthday, {'attr': {'class': 'datepicker form-control', 'placeholder': 'Date of Birth'} }) }}
</div>
{{ form_rest(form) }}
{{ form_end(form) }}
{% endblock %}
The code of the entity :
/**
* @ORM\Column(type="string", nullable=true)
*/
private $birthday;
public function getBirthday(): ?string
{
return $this->birthday;
}
public function setBirthday(?string $birthday): self
{
$this->birthday = $birthday;
return $this;
}
You've got 2 choices:
->format('Y-m-d')
in controller or using
twig's |date('Y-m-d')
filter as $user->getBirthday()
will give you back a DateTime Object.new \DateTime($user->getBirthday()
).When you have your DateTime Object all you need is to create a new one for "today" and calculate the difference from there using DateTime Object's diff()
method or PHP's date_diff()
function.