微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试从用户读取日期以传递给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);

解决方法

我建议你阅读一行文本,使用特定的格式,然后使用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.");
    }
}

如果可以,请使用Java 8 java.time类或Joda Time – 具有相同的基本思想,但使用这些API中的类.两者都比使用日期和日历好得多.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐