The Java input date from scanner is on one line
•
Java
I'm trying to read the date from the user to pass to the Gregorian calendar variable At present, I have an embarrassing setting that reads line by line Can you help a solution to collect input? I found the simpledateformat class, but I couldn't find a class suitable for this particular purpose@ H_ 419_ 7@
Scanner time = new Scanner(system.in) System.out.println("Type year: ");int y =time.nextInt(); System.out.println("Type month: ");int m =time.nextInt(); System.out.println("Type day: ");int d = time.nextInt(); System.out.println("Type hour: ");int h = time.nextInt(); System.out.println("Type minute: ");int mm = time.nextInt(); GregorianCalendar data = new GregorianCalendar(y,m,d,h,mm);
Solution
I suggest you read a line of text, use a specific format, and then use dateformat to parse it For example: @ h_ 419_ 7@
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm",Locale.US); System.out.println("Enter date and time in the format yyyy-MM-ddTHH:mm"); System.out.println("For example,it is Now " + format.format(new Date())); Date date = null; while (date == null) { String line = scanner.nextLine(); try { date = format.parse(line); } catch (ParseException e) { System.out.println("Sorry,that's not valid. Please try again."); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码