0

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)
  • I cannot reproduce exactly. The exception that I get is `java.time.format.DateTimeParseException: Text '19-08-1999' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MinuteOfHour=8, DayOfMonth=19, Year=1999},ISO of type java.time.format.Parsed`. – Ole V.V. Mar 04 '21 at 17:03
  • @Mike B pointed out my error...its "M" instead of m. I believe "m" is used for Minutes – Saraswan Sinha Mar 06 '21 at 10:41
  • It’s true. I have already upvoted Mike’s answer. The answers in the linked original question say the same. – Ole V.V. Mar 06 '21 at 11:10

1 Answers1

2

Months in the DateTimeFormatter are used with capital Ms instead of lowercase m, so your code should be:

DateTimeFormatter dob_format = DateTimeFormatter.ofPattern("dd-MM-uuuu");
Mike B
  • 2,756
  • 2
  • 16
  • 28