I need to make a program in Java that takes date as input in this format - "dd-mm-yyyy". Anything other than that is considered invalid. I understand that there is a LocalDateTime API and a DateTimeFormatter API that java has. However, they are used to parse the date into a specific format after the input is made. Is there any way we can take Date input in a specified format only and not parse it after the input is made? I am quite new to these APIs and am learning, any help will be appreciated. Thanks in advance.
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.swing.text.DateFormatter;
public class Voter_eligibility {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
DateTimeFormatter dob_format = DateTimeFormatter.ofPattern("dd-mm-uuuu");
String input = sc.nextLine();
LocalDate dob = LocalDate.parse(input,dob_format);
System.out.println(dob);
}
}
This is what I did. But it gives an Exception.
19-08-1999
Exception in thread "main" java.time.format.DateTimeParseException: Text '19-08-1999' could not be parsed at index 3
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2051)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1953)
at java.base/java.time.LocalDate.parse(LocalDate.java:429)
at Voter_eligibility.main(Voter_eligibility.java:17)