Write a java program to check Date Validation

Write a program to read a string representing a date. The date can be in any of the three formats

1:dd-MM-yyyy 2: dd/MM/yyyy 3: dd.MM.yyyy

If the date is valid, print  go site valid else print  invalid.

The return type (integer) should be based on the validity of the date.

Input and Output Format:

Input consists of a string.

The output consists of a string.

Refer sample output for formatting specifications.

Sample Input 1:

03.12.2013

Sample Output 1:

valid

Sample Input 2:

03$12$2013

Sample Output 3:

Invalid

Date Validation in Java.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    
    getvalues(s);
  }

  public static void getvalues(String s) {
    if (s.matches("[0-9]{2}[.]{1}[0-9]{2}[.]{1}[0-9]{4}")) {
      SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
      sdf.setLenient(false);
      try {
        Date d1 = sdf.parse(s);
        System.out.println(1);
      } catch (ParseException e) {
        System.out.println(-1);
      }
    } else if (s.matches("[0-9]{2}[/]{1}[0-9]{2}[/][0-9]{4}")) {
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      sdf.setLenient(false);
      try {
        Date d1 = sdf.parse(s);
        System.out.println(1);
      } catch (ParseException e) {
        System.out.println(-1);
      }
    } else if (s.matches("[0-9]{2}[-]{1}[0-9]{2}[-][0-9]{4}")) {
      SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
      sdf.setLenient(false);
      try {
        Date d1 = sdf.parse(s);
        System.out.println(1);
      } catch (ParseException e) {
        System.out.println(-1);
      }
    } else
      System.out.println(-1);
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

15 − three =