Check A Date Valid or not - Java
softetechnologies
27-06-2018    3330 times
Valid Date

Check A Date Valid or not

Write a program accept a date [ Format : dd/MM/yyyy ] from the user. Now check if the received date is a valid date or not . [also check for leap year ].

First of all, we create a integer array of days of every months. Read the day in dd/MM/yyyy format and split it into day, month and year. Now Check the year grater than 1900 and less than 9999 now check this year is leap year or. if leap year the increment 2nd element of the days array. Now check the day from the list of days. if it in the range the declared it a valid date.

import java.util.*;
public class CheckDate
{
    public static void main(String []args)
    {
        Scanner sc=new Scanner(System.in);    
        int days[]={31,28,31,30,31,30,31,31,30,31,30,31};
        String input;
        System.out.print("Enter Date (dd/MM/yyyy) : ");
        input=sc.nextLine();
        int d=Integer.parseInt(input.substring(0,2));
        int m=Integer.parseInt(input.substring(3,5));
        int y=Integer.parseInt(input.substring(6));
        if(y>1900 && y<=9999)
        {
            if(((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
            {
                    days[1]++;
            }
            if(m>0 && m<=12)
            {
                if(d>0 && d< days[m-1])
                {
                    System.out.print("Valid Date");
                }
                else
                {
                   System.out.print("Invalid Date"); 
                }
            }
            else
            {
                   System.out.print("Invalid Date"); 
            }
        }
        else
        {
           System.out.print("Invalid Date"); 
        }
    }
}
softetechnologies
softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post