Age Calc in TWIG or PHP

Hi,
I fully understand that PHP custom code isn’t covered by Theme.co support, but since the issue is similar when using TWIG, I hope you can guide me on how to resolve it in any of these ways.

I have a Custom Post Type “Specialist” with a number of fields. There are two date fields used one to dynamically calculate a person’s current age and the second for years of experience. When I integrate a PHP function or TWIG template to accomplish this, I encounter an unusual issue. Some of the values in the array are processed and calculated properly, but others return an error. I’ve been trying to change date format but none of them worked out. Currently, ‘d/m/Y’ format is used everyware (Word Press defaults for the date format as well as respective ACF fields). What am I doing wrong?

I will provide details on the implementation for TWIG as it is an officially supported feature.

{% set birth_date = acf.post_field({"field":"specialist_birthdate"}) %}
{% set difference = date(endDate).diff(date(birth_date)) %}
{% set age = difference.y %}
	{{ age }}

The code for years of experience is almost the same. Here is what I get for some of the records on the front-end (if PHP function is used I get blank page for the specialist where an error persist):

And here what I get inside Cornerstone:

Here is the link to the specialists archive page for preliminary check of some more examples.

Hello John,

Thanks for writing in!

If the endDate is empty, it may prompt an error. Try adding a condition like for example:

{% set birth_date = acf.post_field({"field":"specialist_birthdate"}) %}
{% if birth_date is not empty and endDate is defined %}
    {% set difference = date(endDate).diff(date(birth_date)) %}
    {% set age = difference.y %}
    {{ age }}
{% else %}
    {# Display a fallback message or nothing #}
    Date information unavailable.
{% endif %}

Hope this helps.

Hi @ruenel,

Thank you very much for providing the complete syntax. However, the question is still the same. What is the reason behind the specialist_birthdate field consistently causing an exception? The fallback message serves its purpose effectively now if that is the case. However, in my case, all respective CPT records have values and are marked as required in the ACF field group. Which means that initially, every CPT record contains required date value, but the calculations for some cases still have an exception which is confusing. There appears to be a syntax error in the ‘if else’ statement. Removing it allows all ‘set’ statements to return the correct values.

{% set birthDate = acf.post_field({"field":"specialist_birthdate"}) %}
	Birth date is {{ birthDate }} and
{% set endDate = date()|date('d/m/Y') %}
  current date is {{ endDate }}.
{% if birthDate is not empty and endDate is defined %}
	{% set difference = date(endDate).diff(date(birthDate)) %}
	{% set age = difference.y %}
    Age equals to {{ age }} full years
{% else %}
    {# Display a fallback message or nothing #}
    (Date information unavailable)
{% endif %}  

On top of that, there is another question. Some of the strings are not calculated correctly and show figures for one year less. This one, for example. If we compare the current date and the birthdate, it should be 60 not 59.

Hey John,

The Date format may need to be defined. Check the mofified code here:

{% set birthDate = acf.post_field({"field":"specialist_birthdate"}) %}
Birth date is {{ birthDate }} and
{% set endDate = date()|date('d/m/Y') %}
current date is {{ endDate }}.

{% if birthDate is not empty and endDate is defined %}
    {% set birthDateTime = date(birthDate, 'd/m/Y') %}
    {% set endDateTime = date(endDate, 'd/m/Y') %}
    {% set difference = endDateTime.diff(birthDateTime) %}
    {% set age = difference.y %}
    Age equals to {{ age }} full years
{% else %}
    (Date information unavailable)
{% endif %}

Hope this helps.

Hi @ruenel,

It seems to me that in the previous code version when I set endDate I applied date format, or it is not enough?

{% set endDate = date()|date('d/m/Y') %}
  current date is {{ endDate }}

Change of the date format when initially set birthDate in the first string doesn’t work in the same way and returns an error.

{% set birthDate = acf.post_field({"field":"specialist_birthdate"})|date('d/m/Y') %}
Birth date is {{ birthDate }}

If I follow your suggestion and use two separate strings for that, I encounter an exception error as well.

{% set birthDate = acf.post_field({"field":"specialist_birthdate"}) %}
{% set birthDateTime = date(birthDate, 'd/m/Y') %}
Birth date is {{ birthDateTime }} 

In any case, your version of the code doesn’t change the outcome.

Hi John,

Here we need to reformat the date value returning from the ACF so it can calculated properly. I have tested this code in your layout and it is showing the correct value.

{% set birthDateString = acf.post_field({"field":"specialist_birthdate"}) %}
{% set parts = birthDateString|split('/') %}
{% if parts|length == 3 %}
    {# Convert to ISO format #}
    {% set isoDate = parts[2] ~ '-' ~ parts[1] ~ '-' ~ parts[0] %}
    
    {# Use date() function to create real DateTime objects #}
    {% set birthDate = date(isoDate) %}
    {% set today = date() %}
    
    {% set age = today.diff(birthDate).y %}
    
    <p>Test Birthdate: {{ birthDateString }}</p>
    <p>ISO Format: {{ isoDate }}</p>
    <p>Birthdate (DateTime): {{ birthDate|date('Y-m-d') }}</p>
    <p>Today: {{ today|date('Y-m-d') }}</p>
    <p>Age: {{ age }} years old</p>
{% else %}
    <p>Invalid date format: {{ birthDateString }}</p>
{% endif %}

I would suggest you use the code in your template and check if that works.

NOTE: Added the code in the Specialized Age(1) element, and set it hidden. You can extract the code from that too.

Thanks

1 Like

Thanks, @tristup, for the detailed code example. :+1:

Apparently dates are much more complex than they seem. I never expected the ACF date format to differ from the settings in the respective field properties as well as its visual output in TWIG…

Hi John,

You are most welcome. Please let us know if you need any further help with this.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.