Scenario
You would like to calculate someone’s age based on their birthday.
Recipe
Add a date field for the birthday
Add a Date Field called Birthday to an Object. We will use a Person Object for this example.
Set the Field’s defaults to "none" and make the Field required.
Add an equation field
Add an Equation Field called Birthday.
-
Set the Equation Type to "Date."
-
Set the Date Type to “years."
-
Make sure the Result Type is set to "Number," which is the default.
-
Use the following equation which subtracts the birthday from the current date:
currentTime() - {Birthday}
.
This will only work for birthdates after 1/1/1970. For handling dates prior to 1/1/1970 as well, please see the "Using a Conditional Equation" section below. - Be sure the rounding is set to "Round Down" so your users aren't having their birthdays before they've actually happened in real time!
Your Equation Field should look like this:
Test the equation
Add a Person record:
...and verify that the equation has worked:
Optional Features
4.1 Using a Conditional Equation
If you would like to make your Birthday field optional or to add an extra layer of protection against bad data, you can use the following conditional equation:
{Birth Date} > -2208988800 ? currentTime() - {Birth Date} : 0
This allows us to ensure that there is actually a value stored for the Birthday Field before running the calculation. If there is no value for the Birthday field, we set Age in Years to zero.
The long negative number (-2208988800) is the epoch timestamp of 1/1/1900. This is required as blank date values, when used in an equation, are treated as 1/1/1970, the timestamp used as Knack's "start" date for date values. This equation ensures that any date prior to 1/1/1970 are evaluated the same as values after that date.