LaVOZs

The World’s Largest Online Community for Developers

'; php - How to calculate age from a string date? - LavOzs.Com

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:

  • 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.
  • 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 ->diff() or date_diff().

Related
How to return only the Date from a SQL Server DateTime datatype
How do you get a timestamp in JavaScript?
Deleting an element from an array in PHP
Compare two dates with JavaScript
Detecting an “invalid date” Date instance in JavaScript
How do I get the current date in JavaScript?
Calculate difference between two dates (number of days)?
How do I get a YouTube video thumbnail from the YouTube API?
How to format a JavaScript date
How do I check if a string contains a specific word?