1
0
-1

Hello Everyone.

On my form I have a date picker to store date of birth, it's called date_of_birth.

I have a text field for age, it's called age.

How can I use the value of date_of_birth (e.g. 08/10/13) to automatically calculate the age (compare difference between date_of_birth and today's date) and the end result would be to automatically put the age in the Age text field (in this case it would be 10)?

I assume it's done using Beanshell, but I am not sure what the code would be or which field of the two to add it to.

Any help is much appreciated - thanks!

    CommentAdd your comment...

    1 answer

    1.  
      3
      2
      1

      It is not recommended at all but you can use a jQuery for that if it is really required. You won't be needing a Beanshell.

      <script>
              $(document).ready(function () {
                  // Date input change event handler
                  $("#birthdate").on("change", function () {
                      var birthdate = new Date($(this).val());
                      var today = new Date();
                      var age = today.getFullYear() - birthdate.getFullYear();
      
                      // Check if birthday has occurred this year
                      if (today.getMonth() < birthdate.getMonth() || (today.getMonth() === birthdate.getMonth() && today.getDate() < birthdate.getDate())) {
                          age--;
                      }
      
                      // Populate the "Age" field
                      $("#age").val(age);
                  });
              });
          </script>



      Usually in a database you don't store values that you can calculate, it can cause issues. For example the Age will change as the current date (today date) changes and you wont be updating age field daily in all the records.
      So I would suggest that you store the DOB and get the Age using that stored DOB.
      You can display Age in the list by using the following SQL command.

      SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),"date_of_birth")), '%Y') + 0 AS age;
      1. Ian Walker

        Thank you for replying.

        If I use the SQL method instead, do I just add the query to the Age text field?

        Thank you very much for your help.

      2. Anas Misbah Shami

        SQL will be used on the datalist. You will use DOB column to get age and display in the front

      CommentAdd your comment...