来自 Scanner 的 Java 输入日期在一行中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28385099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:30:34  来源:igfitidea点击:

Java input date from Scanner in one line

javajava.util.scannergregorian-calendar

提问by Turo

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.

我正在尝试从用户读取日期以传递给 GregorianCalendar 变量。目前我有一个尴尬的设置,它逐行读取。您能帮助解决在一行中收集输入的解决方案吗?我找到了 SimpleDateFormat 类,但找不到适合此特定目的的类。

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

回答by Jon Skeet

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

我建议您阅读具有特定格式的一行文本,然后用于DateFormat解析它。例如:

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.timeclasses, or Joda Time- with the same basic idea, but using the classes from those APIs. Both are muchbetter than using Dateand Calendar.

如果可以,请使用 Java 8java.time类或Joda Time- 具有相同的基本思想,但使用这些 API 中的类。两者都低于使用更好的DateCalendar