Java input date from Scanner in one line

Turo picture Turo · Feb 7, 2015 · Viewed 16.5k times · Source

I'm trying to read date from a user to pass to GregorianCalendar variable. Currently I have an awkward setup, where it reads line by line. Can you help with a solution that collects input in one line? I found SimpleDateFormat class, but I cannot find a good fit for this specific purpose.

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

Answer

Jon Skeet picture Jon Skeet · Feb 7, 2015

I would suggest you read in a line of text, with a specific format, then use DateFormat to parse it. For example:

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.");
    }
}

If you can, use the Java 8 java.time classes, or Joda Time - with the same basic idea, but using the classes from those APIs. Both are much better than using Date and Calendar.