To exemplify this process we will work on writing a program to determine the num
ID: 3641115 • Letter: T
Question
To exemplify this process we will work onwriting a program to determine the number of days between two dates.
Enter first date (M/D/Y): 8/15/2011
Enter second date (M/D/Y): 7/15/2012
Days between 08/15/2011 and 07/15/2012 are 335.
Analyze and decompose the task
1. The input data we need to get from user: two dates, both in numeric month/day/year format. We
will use either Scanner or JOptionPane to get each date from a user and store them into two
variables, say start and end.
2. We need to calculate the number of days between these two dates. Assuming the years are the
same, this can be calculated by transforming each date into the number of days into that year
(1/16/2012 ? 16, 2/16/2012 ? 47, etc.) and subtracting (47
Explanation / Answer
please rate - thanks
message me if any problems
import java.util.Scanner;
/**
* Days determines the number of days between two dates.
* @author X
* @version 1.0, 2012/03/DD
*/
public class Days {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int month,day,year,days;
int month2,day2,year2;
System.out.print("Enter first date (M/D/Y): ");
String start=in.nextLine();
Scanner scanDate1 = new Scanner(start);
scanDate1.useDelimiter("/");
month = scanDate1.nextInt();
day = scanDate1.nextInt();
year = scanDate1.nextInt();
System.out.print("Enter second date (M/D/Y): ");
String end = in.nextLine();
Scanner scanDate2 = new Scanner(end);
scanDate2.useDelimiter("/");
month2 = scanDate2.nextInt();
day2 = scanDate2.nextInt();
year2 = scanDate2.nextInt();
System.out.printf("Days between %s and %s are %d. ", start, end,daysBetweenDates(month,day,year,month2,day2,year2));
}
public static int leap(int year)
{int leapcode=0;
if(year%4==0)
{if(year%100!=0)
leapcode=1;
else
if(year%400==0)
leapcode=1;
}
return leapcode;
}
public static int daysinmonth(int month)
{switch(month+1)
{case 4:case 6:case 9:case 11: return 30;
case 2: return 28;
default: return 31;
}
}
public static int todoy(int month,int day,int year)
{int days=0,i;
for (i=0;i<month-1;i++)
days+=daysinmonth(i);
days+=day;
if(days>59) //feb 28 is day 59
days=days+leap(year);
return days;
}
public static int daysBetweenDates(int month,int day, int year,int month2,int day2,int year2) {
int days = 0;
int j,doy,doy2;
doy=todoy(month,day,year);
doy2=todoy(month2,day2,year2);
if(year==year2)
days=doy2-doy;
else
{for(j=year+1;j<=year2-1;j++) //more than a year apart
days=days+365+leap(j);
days=365+leap(year)-doy+doy2+days; //2 years continuous
}
return days;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.