Program to calculate age

In this article, you will learn to write a program to calculate age. That means, if the given two dates are dt1 and dt2, you need to calculate the difference between the two dates in years, months, and days. But make sure that the dt1 is earlier than the dt2.

For example,

Input : 
Birth date = 23/8/2022 
Current date = 12/1/2023


Output :
Age: 0 years 04 months and 20 days

 

Disclaimer: In my code date is only valid if lying in the range of 1800 to 9999 and the birth date should be equal to or less than the current date. You can change it as per your requirement.

 

Approach (Using Subtraction):

Follow the below steps to solve the problem: But you should try the problem yourself first.

  • First, validate the birth date, it should be less than or equal to the current date. Because it is a primary prerequisite.
  • Check both birth and current date or valid date or not.
  • Now calculate the difference in years, months and days. But when calculating the difference between two dates you need to just keep track of two conditions.
  • If the current date is less than that of the birth date, then that month is not counted, and for subtracting dates you need to add the number of month days to the current date so as to get the difference in the dates.
  • If the current month is less than the birth month, then that year is not counted, and for subtracting months you need to add the 12 to the current month so as to get the difference in the months.

 

C Program program to calculate age:

The following is a C program to calculate age in years, months, and days. You must need to enter the date in the format of mentioned structure (SDate).

#include <stdio.h>

#define MAX_YR  9999
#define MIN_YR  1800
#define INVALID_YEAR -1
#define INVALID_OUTPUT -1


//structure for day, month, year
typedef struct
{
    int dd;
    int mm;
    int yy;
} SDate;

// Function to check leap year.
//Function returns 1 if leap year
int  isLeapYear(int year)
{
    return (((year % 4 == 0) &&
             (year % 100 != 0)) ||
            (year % 400 == 0));
}

//return 1 if birth date less than current date
int isCDateLessThanDob(const SDate *const pDob, const SDate *const pCDate)
{
    int retVal = (pCDate->yy <= pDob->yy);
    retVal = retVal ? (pCDate->mm <= pDob->mm):retVal;
    retVal = retVal ? (pCDate->dd < pDob->dd):retVal;
    return (retVal);
}

// returns 1 if given date is valid.
int validDate(const SDate *const pValidDate)
{
    //check range of year,month and day
    if ((pValidDate->yy > MAX_YR) ||
            (pValidDate->yy < MIN_YR))
        return 0;
    if ((pValidDate->mm) < 1 || (pValidDate->mm) > 12)
        return 0;
    if ((pValidDate->dd) < 1 || (pValidDate->dd) > 31)
        return 0;
    //Handle feb days in leap year
    if ((pValidDate->mm) == 2)
    {
        if (isLeapYear(pValidDate->yy))
            return ((pValidDate->dd) <= 29);
        else
            return ((pValidDate->dd) <= 28);
    }
    //handle months which has only 30 days
    if (pValidDate->mm == 4 || pValidDate->mm == 6 ||
            pValidDate->mm == 9 || pValidDate->mm == 11)
        return ((pValidDate->dd) <= 30);
    return 1;
}


//number of days in month
const int monthDays[12]
    = { 31, 28, 31, 30, 31, 30,
        31, 31, 30, 31, 30, 31
      };


// Function returns age in years, month and days.
int ageCalculator(const SDate *const pDobDate,
                  SDate * const pCurrentDate, SDate *pAge)
{
    int retVal = INVALID_OUTPUT;
    if((pDobDate == NULL) && (pCurrentDate == NULL))
    {
        return retVal;
    }
    int isDateValid = (0 == isCDateLessThanDob(pDobDate,pCurrentDate));
    isDateValid = isDateValid? validDate(pDobDate):isDateValid;
    isDateValid=  isDateValid? validDate(pCurrentDate):isDateValid;
    if(isDateValid)
    {
        retVal = 0;

        // if current date is less than birth day date
        // then do not count birth day month and add this
        // month days as an extra day.
        if((pCurrentDate->dd) < (pDobDate->dd))
        {
            int extraDay = monthDays[pDobDate->mm-1];
            extraDay += isLeapYear(pCurrentDate->yy)? 1: 0;
            pCurrentDate->dd+= extraDay;
            pCurrentDate->mm-=1;
        }
        //calculate day
        pAge->dd = (pCurrentDate->dd)- (pDobDate->dd);

        // if current month less than birth month, then do
        // not count this year and add 12 to the month so
        // that we can subtract and find out the difference
        if((pCurrentDate->mm) < (pDobDate->mm))
        {
            pCurrentDate->mm+=12;
            pCurrentDate->yy-=1;
        }
        //calculate month and year
        pAge->mm = (pCurrentDate->mm)-(pDobDate->mm);
        pAge->yy = (pCurrentDate->yy)-(pDobDate->yy);
    }
    else
    {
        printf("Date is invalid.\n");
    }

    return retVal;
}


int main()
{
    // formate of dd, mm, yy
    SDate dobDate = {24, 5, 2019};
    SDate currentDate = {12, 1, 2023};
    SDate age = {0} ;

    //calling function
    const int retVal = ageCalculator(&dobDate,&currentDate,&age);
    if(retVal != INVALID_OUTPUT)
    {
        printf("\nAge: %d years %02d months and %02d days\n\n",
               age.yy, age.mm, age.dd);
    }
    return 0;
}

Output:

Age: 3 years 07 months and 19 days

 

Recommended Post: