+92 332 4229 857 99ProjectIdeas@Gmail.com

Age calculator (C++)


Age calculator
It gives your age in number of days starting from your date of birth to the current date.
Date class has 2 types of constructors:
Date() initializes the date with the current date.
See how to get the current date:

Date(int,int,int) initializes the date with the specified date.
Functions in the Date class are:
displayDate() displays the date.
ageInDays() takes Date as an input parameter and returns your age in days.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "time.h"

using namespace std;

class Date
{
private:
public:
int day,month,year;
Date();
Date(int,int,int);
void displayDate();
int ageInDays(Date);
};

Date::Date()
{
struct tm *ptr;   
time_t sec;       
time(&sec);       
ptr=localtime(&sec);

month = (short) ptr->tm_mon + 1;
day   = (short) ptr->tm_mday;
year  = (short) ptr->tm_year + 1900;
}

Date::Date(int d,int m,int y)
{
day=d;
month=m;
year=y;
}

int monToNoOfDays(int mon)
{
if(mon==1)
return 31;
if(mon==2)
return 28;
if(mon==3)
return 31;
if(mon==4)
return 30;
if(mon==5)
return 31;
if(mon==6)
return 30;
if(mon==7)
return 31;
if(mon==8)
return 31;
if(mon==9)
return 30;
if(mon==10)
return 31;
if(mon==11)
return 30;
if(mon==12)
return 31;
return 0;
}

void Date::displayDate()
{
cout<<day<<"/"<<month<<"/"<<year;
}

int Date::ageInDays(Date D2)
{
int yearDiff=D2.year-year;
int monDiff=D2.month-month;
int totalDays=0;
int finalAgeInDays=0;
int temp1Days=0;
int temp2Days=0;

if(yearDiff==0)
{
if(monDiff==0)
{
finalAgeInDays=D2.day-day;
}
else if(monDiff>0)
{

int noOfDays=0;
for(int i=month;i<D2.month;i++)
{
if(year%4==0&i==2)
noOfDays+=1;

noOfDays+=monToNoOfDays(i);
}
finalAgeInDays=noOfDays;
}
}
else if(yearDiff>0)
{
int noOfDays1=monToNoOfDays(month);
if(year%4==0&month==2)
noOfDays1+=1;

int remDays1=noOfDays1-day;
temp1Days=remDays1;

for(int i=month+1;i<=12;i++)
temp1Days+=monToNoOfDays(i);

for(int i=year+1;i<D2.year;i++)
{
if(i%4==0)
totalDays+=366;
else
totalDays+=365;
}

temp2Days=D2.day;
for(int i=D2.month-1;i>0;i--)
{
if(i%4==0&D2.month==2)
temp2Days+=1;

temp2Days+=monToNoOfDays(i);
}                     
finalAgeInDays=temp1Days+totalDays+temp2Days;
}
return finalAgeInDays;
}

int main()
{
Date D1(22,9,1991);
Date D2;
D1.displayDate();
cout<<endl;
D2.displayDate();
cout<<endl;

int noOfDays=D1.ageInDays(D2);
cout<<noOfDays<<endl;

_getche();
return 0;
}
Output
22/9/1991
14/2/2011
7085

0 comments: