Write a program to accept 2 dates in the string format dd/mm/yyyy and find the difference in days between the 2 dates.
import java.util.*;
public class DateDiff {
int d, m, y;
DateDiff(String date) {
int[] ind = { date.indexOf('/'), date.lastIndexOf('/') };
d = Integer.parseInt(date.substring(0, ind[0]));
m = Integer.parseInt(date.substring(ind[0] + 1, ind[1]));
y = Integer.parseInt(date.substring(ind[1] + 1));
}
int getDaysofMonth() {
int res = 0;
int[] DAY_COUNT = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (y % 4 == 0)
DAY_COUNT[1]++;
for (int x = 1; x < m; x++)
res += DAY_COUNT[x - 1];
return res;
}
int subtract(DateDiff b) {
int d = b.getDaysofMonth() + b.d - (this.getDaysofMonth() + this.d);
if (b.y - this.y != 0) {
int bg = Math.max(b.y, this.y);
int sm = Math.min(b.y, this.y);
for (int x = sm; x < bg; x++)
if (x % 4 == 0)
d += 366;
else
d += 365;
}
return d;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Date 1: ");
DateDiff d1 = new DateDiff(sc.next());
System.out.print("Date 2: ");
DateDiff d2 = new DateDiff(sc.next());
System.out.printf("Difference: %d days", d1.subtract(d2));
sc.close();
}
}
Name | Type | Use |
---|---|---|
global | ||
d | int | to store date |
m | int | to store month |
y | int | to store year |
int getDaysofMonth() | ||
res | int | Resultant value which will be returned later on in the function |
DAY_COUNT | in[] | Integer array storing the number of days of the 12 months |
int subtract() | ||
b | DateDiff | the object of the date from which the current date has to be |
subtracted | ||
d | int | stores the difference in number of days between the dates |
bg | int | store the year of gretater numerical value |
sm | int | store the year of smaller numerical value |
void main | ||
sc | Scanner | to take user input |
d1 | DateDiff | Objecr to store first date |
d2 | DateDiff | Objecr to store second date |