A child was born on 31/12/1999. The current date has been provided as input in "dd/mm/yyyy" format. What is the age of the child in days. Note that the current date will be later than 31/12/1999
ageInDays("01/01/2000")=1
ageInDays("30/03/2013") = 4838
Please comment if you find any mistake.
ageInDays("01/01/2000")=1
ageInDays("30/03/2013") = 4838
public class AgeOfChild {
static String testcase1 = "1/1/2012";
public static void main(String args[]){
AgeOfChild
testInstance= new AgeOfChild();
int result =
testInstance.ageInDays(testcase1);
System.out.println("Result :
"+result);
}
//write your code
here
public int ageInDays(String
date){
String
DateOfBirth="31/12/1999";
int
birthMonthDays=findingDaysInYear(DateOfBirth);
int
birthYear=findYear(DateOfBirth);
System.out.println(birthMonthDays);
if((birthYear%4==0
&& birthYear%100!=0 ) || (birthYear%100==0 &&
birthYear%400==0)){
birthMonthDays=366-birthMonthDays;
}
else{
birthMonthDays=365-birthMonthDays;
}
int
endMonthDays=findingDaysInYear(date);
int
endYear=findYear(date);
int
daysInBetweenYear=findingDaysInBetweenYear(birthYear,endYear);
return
((birthMonthDays+daysInBetweenYear+endMonthDays));
}
//finding days
between the starting year and ending year
private int
findingDaysInBetweenYear(int birthYear, int endYear) {
int days=0;
for(int
i=birthYear+1;i<endYear;i++){
if((i%4==0 &&
i%100!=0 ) || (i%100==0 && i%400==0)){
days=days+366;
}
else{
days=days+365;
}
}
return days;
}
// finding year of
the date
private int findYear(String str)
{
int len=str.length();
int year=0;
for(int
i=len-4;i<len;i++){
char ch=str.charAt(i);
year=year*10+ch-'0';
}
return year;
}
//finding days in a
particular year as per given date
private int
findingDaysInYear(String str){
int len=str.length();
int days=0;
int month=0;
int year=0;
String
strNew="";
int num=0;
int count=0;
//splitting string
to find month,days and year
for(int i=0;i<len;i++){
char ch=str.charAt(i);
if(ch=='/' &&
count==0){
days=num;
num=0;
count++;
}
if(ch=='/' &&
count==1){
month=num;
num=0;
}
else if(i==len-1){
num=num*10+ch-'0';
year=num;
}
else{
num=num*10+ch-'0';
}
}
int
daysInyear=findingDays(days,month,year);
return daysInyear;
}
//helping method
for the method(findigDaysInYear) to find days in a year
private int findingDays(int days, int month, int year) {
int totaldays=0;
for(int i=1;i<month;i++)
{
if(i==1 ||i==3|| i==5
|| i==7 || i==8 ||i==10 || i==12 ){
totaldays=totaldays+31;
}
else if(i==2 &&
((year%4==0 && year%100!=0 ) || (year%100==0 && year%400==0))){
totaldays=totaldays+29;
}
else if(i==2){
totaldays=totaldays+28;
}
else{
totaldays=totaldays+30;
}
}
totaldays=totaldays+days;
return totaldays;
}
}
Please comment if you find any mistake.
No comments:
Post a Comment