Calculate user's age using BirthDay field

 

RSForm!Pro comes with a built-in BirthDay field to use in your forms. Depending on your needs, there may be times when you wish to calculate and store the user's current age. Such scenario can be implemented as instructed below:

 

1. Fields

  • the BirthDay field: for users to submit their birthday
  • 3 hidden fields: used to store the submitter's age, one for the Years, for the Months and one for the Days
 

After the form is submitted, you can use the hidden field's placeholder within the thank-you-message page or the RSForm!Pro generated emails. The placeholder should be similar to: {years:value} / {months:value} / {days:value}

 

2. Script

The following script is added within the "Scripts Called On Form Process" area (backend > Components > RSForm!Pro > Manage Forms > your form > Properties > PHP Scripts). More information on RSForm!Pro PHP Scripts here.

$myBdField = $_POST['form']['my-bday-field-name'];

$selected_date = $myBdField['y'].'-'.$myBdField['m'].'-'.$myBdField['d'];
$current_date = date('Y-m-d');

$selected_date_seconds = strtotime($selected_date);
$current_date_seconds = strtotime($current_date);

if ($current_date_seconds > $selected_date_seconds) {
  $selected_date = new DateTime($selected_date); //starting seconds
  $current_date = new DateTime($current_date); // ending seconds

  $interval =  date_diff($current_date, $selected_date); //the time difference

  $years = (int) $interval->format('%y');
  $months = (int) $interval->format('%m');
  $days = (int) $interval->format('%d');
}
else 
{
  $years = 0;
  $months = 0;
  $days = 0;
}

$_POST['form']['years'] = $years;
$_POST['form']['months'] = $months;
$_POST['form']['days'] = $days;
Remember to replace:
my-bday-field-name : with your BirthDay field exact name.
'years', 'months', 'days' : with your hidden fields exact names.

5 persons found this article helpful.


Was this article helpful?

Yes No
Sorry about that

You Should Also Read

Set up conditionals for groups of fields HOT

Fields are not showing up in the frontend HOT

How to copy information from other fields

Display Last Edited Date in Submissions Directory