Search code examples
jekyllliquid

How do I show current age using liquid?


I have a Jekyll website about my pets. I want it to automatically update my pet's age based on their birthday. I cannot, for the life of me, figure out the liquid formula to show their age based on today's date and their birthday.

What is the right liquid formula to show this?


Solution

  • You can either use JS with libraries like moment to compute the birthday client-side, like this:

    const pet_birthday_element = document.querySelector("#pet_birthday");
    const pet_age_element = document.querySelector("#pet_age");
    const pet_age = moment().diff(pet_birthday_element.innerText, 'years');
    
    pet_age_element.innerText = `Your pet is ${pet_age} years old!`;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    
    Your per birthday is: <span id="pet_birthday">2020-07-10 15:00:00.000</span>
    <div id="pet_age"></div>

    Or, if you prefer a strict liquid approach, David Jacquel had a nice solution in a different thread. He turns both the birthday and the current date into timestamps (number of seconds), then substracts one from the other, and displays the difference, something like this:

    {% assign dateStart = "2020-04-09" | date: '%s' %}
    {% assign nowTimestamp = 'now' | date: '%s' %}
    
    {% assign diffSeconds = nowTimestamp | minus: dateStart %}
    {% assign diffDays = diffSeconds | divided_by: 3600 | divided_by: 24 | divided_by: 365 %}
    
    <div>Your pet is {{ diffDays | round: 0 }} years old!</div>
    

    You can test it here.