Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java input date from Scanner in one line

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);
like image 941
Turo Avatar asked Mar 08 '26 15:03

Turo


1 Answers

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.

like image 187
Jon Skeet Avatar answered Mar 10 '26 04:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!