How to check if a given date is valid or not in Java?
Verify the validity of a given date. It can be presumed that perhaps the given date falls between January 1, 1800, and December 31, 9999.
Examples :
Input : d = 31, m = 12, y = 2005
Output : Yes
Since 31st December is the valid date
Input : d = 31, m = 2, y = 2001
Output : No
Since 31st February is invalid. The
February month cannot have 31 days.
The concept is basic. We must take care of the following.
1) y1, m1, and d1 are within acceptable bounds.
2) February's days fall within the permitted range, while leap year is taken into account.
3) The handling of days over 30 day months.
The implementation to determine whether a given year is legitimate is shown below.
Code:
FileName: DateChecker.java
// A Java program to
// determine whether a
// given date is valid.
import java.io.*;
class DateChecker
{
static int MAX_VALID_YR = 9998;
static int MIN_VALID_YR = 1801;
// Returns true if
// given year is a valid year.
static boolean isLeap(int y)
{
// Return true if the year is
// a multiple of 4 and not
// multiple of 100.
// OR year is multiple of 400 it again returns true.
return (((y % 4 == 0) &&
(y % 100 != 0)) ||
(y % 400 == 0));
}
// Returns true if given
// year is valid or not.
static boolean isValidDate(int d1,
int m1,
int y1)
{
// If year, month, and day
// are not in a given range
// then return false
if (y1 > MAX_VALID_YR ||
y1 < MIN_VALID_YR)
return false;
if (m1 < 1 || m1 > 12)
return false;
if (d1 < 1 || d1 > 31)
return false;
// Handling February month
if (m1 == 2)
{
if (isLeap(y1))
return (d1 <= 29);
else
return (d1 <= 28);
}
// Months of April, June,
// September and November must have
// days less than
// or equal to 30.
if (m1 == 4 || m1 == 6 ||
m1 == 9 || m1 == 11)
return (d1 <= 30);
return true;
}
// Main code
public static void main(String args[])
{
if (isValidDate(31, 12, 2005))
System.out.println("Yes");
else
System.out.println("No");
if (isValidDate(30, 2, 2000))
System.out.println("Yes");
else
System.out.println("No");
}
}
Output:
Yes
No
The Time Complexity of the above code is O(1).
Auxiliary Space is O(1).