Search code examples
javasimpledateformat

User Input date giving error when parsed to SimpeDateFormat


I am trying to input the date from the user. But the code is giving error at the parse method. The code I am trying is below.

import java.util.*;
import java.text.SimpleDateFormat;

public class date_parse {
    public static void main(String args[]) {
        Scanner input=new Scanner(System.in);
        String s=input.nextLine();
        SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
        System.out.println(f.parse(s));
    }   
}

NOTE -: The code is running well if I directly provide string format date like "01-01-2000" in place os s in parse method


Solution

  • First of all you don't name your class like that in Java. Please go through this article to know more about naming conventions in Java. Secondly as Risalat Zaman mentioned the parse method throws ParseException which need to be handled in your code. Try changing your code as follows:

    public class DateParse {
        public static void main(String args[]) {
            Scanner input=new Scanner(System.in);
            String s=input.nextLine();
            SimpleDateFormat f= new SimpleDateFormat("dd-MM-yyyy");
            try {
                System.out.println(f.parse(s));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }