Is there any simple way to use Scanner and place it into a variable of type GregorianCalendar or to convert the string into a GregorianCalendar? Specifically, I need the user to enter a date in the format mm/dd/yyyy on one line, and a starting and ending time on another (user doesn't have to enter an ending time if the event has none) in the form of a 24 hour clock (eg. 15:30 = 3:30pm).
Anyone have any ideas? All I see online is how to print a GregorianCalendar in different string formats.
Use SimpleDateFormat
. This class is mean to convert String
into java.util.Date
and vice versa.
Here's a brief example:
//initialize the Scanner
Scanner scanner = new Scanner(System.in);
//read the desired input
String dateAsString = scanner.next();
//create an instance of SimpleDateFormat
//MM: month (2 digits)
//dd: day (2 digits)
//yyyy: year (four digits)
//more of this in the javadoc
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//parse the String as a Date
Date desiredDate = sdf.parse(dateAsString);
//Calendar.getInstance() should return a GregorianCalendar instance by "default"
Calendar calendar = Calendar.getInstance();
//setting the date into the Calendar
calendar.setTime(desiredDate);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.