I have proceeded this way to get the age by decrementing the year of birthdate from current year.Is this the right way?

  global class AgeInputBatch implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext bc)
    return Database.getQueryLocator([Select Id,Birthdate from Contact]);
    global void execute(Database.BatchableContext bc,List<Contact>cList){
            for(contact co:cList){
            Integer r=((Integer)Date.today().year() - (Integer)co.Birthdate.year());
    update cList;
    global void finish(Database.BatchableContext bc){
       System.debug('Age is updated');
  • 1
    What do you mean "is this the right way"? is it working the way you want it to? if not, what part of it isn't working? Are you getting any error messages? Please edit your question with more detail about the specific problem you're trying to solve.
    – Nick Cook
    Jan 12 at 5:57
  • You corrected some issues pointed out by Nagendra in comments (which I have removed because they no longer apply), but the real problem is what Derek explained in his answer: your logic is simply incorrect; that's not how you calculate a person's age. And, as he said, a batch class is the wrong solution to this problem.
    – David Reed
    Jan 12 at 6:04
  • Is there a reason a formula field can't be used for this? A person's birthdate is static, but their age changes practically all of the time. A formula will give you a person's age in real time. The only reason I could see of storing an age value in a field is for an integration, and even then there are better ways to go about getting age because you can always calculate it so long as you know the current data and a birth date.
    – nbrown
    Jan 12 at 14:45

Well, you're getting an approximation of a person's age by only focusing on the year. If a Contact's birthday would be on December 31st, though, you'd get a result saying that they are one year older than they truly are.

Maybe that's acceptable in your situation, but if it's not you'll need to add checks against the month and day as well (leading to you subtracting 1 year at most).

Beyond that, there's little reason to use batch apex to handle this. It's a simple enough task that you should strongly consider creating a formula field instead (which would always return an up-to-date result, and wouldn't require a unit test).

  • Sir as you said I am focussing on the year only and I have done it in formula field but also trying to do it using batch class.New to it.
    – user110064
    Jan 11 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.