Date Validation in Java

DateValidationMethod.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package extract_filename;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;


public class DateValidationMethod
 {
        static boolean isLegalDate(String s)
    {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // set the date format here

            sdf.setLenient(false); // this will make the parse method throw ParseException when the given input string is not in the specified format.

            return sdf.parse(s, new ParsePosition(0)) != null;
      }
        
        public static void main(String args[])
        {
            String date_pattern="2004-06-1";
            boolean flag=isLegalDate(date_pattern);
            //System.out.println("flag::"+flag);
            if(flag==true)
            {
                System.out.println("Valid Date");
            }
            else
            {
                System.out.println("Not Valid Date");
            }
            System.out.println("isLegalDate::"+isLegalDate(date_pattern)); //isLegalDate
             }
}


Output:
Valid Date
isLegalDate::true

No comments:

Post a Comment