Search code examples
phpsymfonydatedatetimepicker

How to calculate age from a string date?


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;
}

Solution

  • You've got 2 choices:

    • Change the birthday to a field of type datetime and use BirthdayType in your form. Then you'll have to format the field when you want to show it as string with ->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.
    • Create a new DateTime Object from the string in that field when you want to calculate the age (ie: 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.