How to set a date as input in java?

user3159060 picture user3159060 · Dec 20, 2014 · Viewed 97.3k times · Source

Is there any direct way to set a date to a variable but as an input? I mean that i don't know the date at design time, the user should give it. I tried the following code but it doesn't work: Calendar myDate=new GregorianCalendar(int year, int month , int day);

Answer

sitakant picture sitakant · Dec 20, 2014

Try the following code. I am parsing the entered String to make a Date

// To take the input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Date ");

String date = scanner.next();

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date2=null;
try {
    //Parsing the String
    date2 = dateFormat.parse(date);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(date2);