来自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中的类.两者都比使用日期和日历好得多.
标签:gregorian-calendar,java-util-scanner,java 来源: https://codeday.me/bug/20190728/1559839.html