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);
Scanner sc = new Scanner(System.in); ToolBox. readDate(sc, "YYYY-MM-DD"); ToolBox. readDate(sc, "YYYY-MM-DD HH:mm:ss"); ToolBox. readDate(sc, "YYYY-MM-DD"); sc.
Calendar to initialize date: Calendar calendar = Calendar. getInstance(); //To Initialize Date to current Date Date date = calendar. getTime(); //To Initialize Date to a specific Date of your choice (here I'm initializing the date to 2022-06-15) calendar.
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);
LocalDate.of( 2026 , 1 , 23 ) // Pass: ( year , month , day )
Some other Answers are correct in showing how to gather input from the user, but use the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
LocalDate
For a date-only value without time-of-day and without time zone, use the LocalDate
class.
LocalDate ld = LocalDate.of( 2026 , 1 , 23 );
Parse your input strings as integers as discussed here: How do I convert a String to an int in Java?
int y = Integer.parseInt( yearInput );
int m = Integer.parseInt( monthInput ); // 1-12 for January-December.
int d = Integer.parseInt( dayInput );
LocalDate ld = LocalDate.of( y , m , d );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Maybe you can try my simple code below :
SimpleDateFormat dateInput = new SimpleDateFormat("yyyy-MM-dd");
Scanner input = new Scanner(System.in);
String strDate = input.nextLine();
try
{
Date date = dateInput.parse(strDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
}
catch (ParseException e)
{
System.out.println("Parce Exception");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With