Java – How to set a date as input in java

calendardategregorian-calendarjava

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);

Best Answer

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);