Given a date, check if it is valid or not. It may be assumed that the given date is in range from 01/01/1800 to 31/12/9999.
import java.util.*;
public class DateVerify {
final int[] MIN_DATE = { 1, 1, 1800 };
final int[] MAX_DATE = { 31, 12, 9999 };
final int[] DAY_COUNT = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public int[] d = new int[3];
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter day as dd: ");
d[0] = sc.nextInt();
System.out.print("Enter month as mm: ");
d[1] = sc.nextInt();
System.out.print("Enter year as yyyy: ");
d[2] = sc.nextInt();
sc.close();
}
boolean verify() {
if (!(d[2] >= MIN_DATE[2] && d[2] <= MAX_DATE[2]))
return false;
if (d[0] < 1 || d[1] < 1 || d[1] > 12)
return false;
boolean isLeap = d[2] % 4 == 0;
if (d[1] == 2 && isLeap && d[0] == 29)
return true;
else if (d[0] > DAY_COUNT[d[1] - 1])
return false;
// checking for strict range
if (d[2] == MIN_DATE[2] && d[1] == MIN_DATE[1] && d[0] < MIN_DATE[0])
return false;
else if (d[2] == MAX_DATE[2] && d[1] == MAX_DATE[1] && d[0] > MAX_DATE[0])
return false;
return true;
}
public static void main(String[] args) {
DateVerify a = new DateVerify();
a.input();
System.out.printf("The given date %d/%d/%d is %s Date\n", a.d[0], a.d[1], a.d[2],
(a.verify() ? "a Valid" : "an Invalid"));
}
}
Name | Type | Uses |
---|---|---|
global | ||
d | int[] | integer array of size 3 to store date |
MIN_DATE | int[] | integer array storing minimum possible date |
MAX_DATE | int[] | integer array storing maximum possible date |
DAY_COUNT | int[] | this stores the day count for 12 months of the year |
void main() | ||
a | DateVerify | object to call method |
void input() | ||
sc | Scanner | to take user Input |