0% found this document useful (0 votes)
9 views6 pages

Worksheet 6

Yshabbsbebbdndnsnnshsvsvd

Uploaded by

amandm1200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Worksheet 6

Yshabbsbebbdndnsnnshsvsvd

Uploaded by

amandm1200
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Prayagraj

Session 2020-2021

Round 10

Subject : Computer Science

Class : XI

Worksheet 6
Question:
Write a program to accept 2 dates in the string
format dd/mm/yyyy and find the difference in days
between the 2 dates.

Example:
INPUT:
Date 1 : 20/12/2012
Date 2 : 11/02/2013

OUTPUT: Difference = 54 days


The program should include the part for validating
the inputs namely the date and the day on
1st January of that year.

Program Code :
// The class Date_Difference inputs 2 dates and finds
the difference between them

import java.util.*;
class Date_Difference
{
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
//function for checking for Leap Year

int isLeap(int y)
{
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
return 29;
else
return 28;
}

//function for checking date validation

boolean dateValidate(int d, int m, int y)


{
month[2]=isLeap(y);
if(m<1 || m>12 || d<1 || d>month[m] || y<1000
|| y>9999)
return false;
else
return true;
}

//function for finding day number from year = 1 till the


inputted year

int dayno(int d, int m, int y)


{
int dn=0;
month[2]=isLeap(y);
for(int i=1;i<m;i++)
{
dn=dn+month[i];
}
dn=dn+d;
for(int i=1000;i<y;i++)
{
if(isLeap(i)==29)
dn=dn+366;
else
dn=dn+365;
}
return dn;
}

public static void main(String args[])


{
Scanner sc= new Scanner(System.in);
Date_Difference ob=new Date_Difference();
System.out.print("Enter the 1st date in
(dd/mm/yyyy) format: ");
String date1=sc.nextLine().trim();
int p,q;
//Extracting the day
p=date1.indexOf("/");
int d1=Integer.parseInt(date1.substring(0,p));

//Extracting the month


q=date1.lastIndexOf("/");
int m1=Integer.parseInt(date1.substring(p+1,q));

//Extracting the year


int y1=Integer.parseInt(date1.substring(q+1));

System.out.print("Enter the 2nd date in


(dd/mm/yyyy) format: ");
String date2=sc.nextLine().trim();
p=date2.indexOf("/");
int d2=Integer.parseInt(date2.substring(0,p));
q=date2.lastIndexOf("/");
int m2=Integer.parseInt(date2.substring(p+1,q));
int y2=Integer.parseInt(date2.substring(q+1));

//Validating both the dates

if(ob.dateValidate(d1,m1,y1)==true &&
ob.dateValidate(d2,m2,y2)==true)
{
int a=ob.dayno(d1,m1,y1);
int b=ob.dayno(d2,m2,y2);
System.out.print("Output : Difference =
"+Math.abs(a-b)+" days.");
}
else
System.out.println("Invalid Date");
}
}

You might also like