One of the most common real-world use cases in any app is age validation. Whether it’s signing up for a service, accessing adult content, or like in this case checking if someone is eligible to vote, the logic is always the same: calculate the person’s age and compare it to the legal threshold.
In this blog post, we’ll write a simple Apex method that determines whether a person can vote or not based on their date of birth. If they’re 18 years or older, we return true
. Otherwise, we return false
.
It’s a perfect little challenge if you’re learning Apex and want to understand how date calculations and conditional logic work in Salesforce.
🧠 What Are We Trying to Do?
Let’s say you have a system that collects a person’s date of birth, and you want to know if they are eligible to vote. In most countries, the minimum voting age is 18. So, our method will:
Accept a Date of Birth
Calculate the approximate age based on today’s date
Return
true
if the person is 18 or older, otherwise returnfalse
Simple enough let’s walk through how to do this in Apex.
🔍 Code Explanation
public with sharing class ApexUseCaseSix {
public static Boolean checkVotingRights(Date dateOfBirth){
We define a class named ApexUseCaseSix
and inside it, a static method checkVotingRights
that accepts a Date
input (the person’s date of birth).
Date todaysDate = System.today();
We fetch the current date using System.today()
. This gives us today’s date in Salesforce’s internal date format.
Integer approxAgeInYears = (dateOfBirth.daysBetween(todaysDate))/365;
Next, we calculate the number of days between the date of birth and today. We divide it by 365
to convert it into approximate years.
⚠️ Note: This is a quick approximation and may not account for leap years or exact birth dates — but it works well for general eligibility checks.
if(approxAgeInYears >= 18){
return true;
}
return false;
}
}
We use a simple if
condition to check if the person is at least 18. If yes, we return true
, indicating the person is eligible to vote. If not, we return false
.
✅ Why This Is Useful
This method is a perfect example of how you can:
Work with dates in Apex
Perform simple age calculations
Use conditional logic to return different outcomes
You can easily plug this into a registration form, a validation flow, or any logic where age verification is required — not just voting!
🧾 Final Code Snippet
public with sharing class ApexUseCaseSix {
public static Boolean checkVotingRights(Date dateOfBirth){
Date todaysDate = System.today();
Integer approxAgeInYears = (dateOfBirth.daysBetween(todaysDate))/365;
if(approxAgeInYears >= 18){
return true;
}
return false;
}
}
🎥 Watch It in Action!
Prefer seeing it in action? Watch this short video where I explain the code and test it in Salesforce Developer Console.