来自扫描器的Java输入日期在一行中
问题描述:
我正在尝试从用户读取日期以传递给GregorianCalendar变量。目前我有一个尴尬的设置,它逐行阅读。你能帮助解决方案收集一行中的输入吗?我找到了SimpleDateFormat类,但是我找不到适合这个特定目的的类。来自扫描器的Java输入日期在一行中
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的类。两者都是多好于使用Date
和Calendar
。
嗨,乔恩,我明白有可能有一些更好的解决方案。同时我还在学习,我检查了你的解决方案,看起来“日期”不是在GregorianCalendar中构造函数接受的格式(我已经使用了GregorianCalendar)。所以如果还有其他的解决方案(并不难),我会很感激。谢谢你的方式。 – Turo 2015-02-07 18:06:01
@Turo:在构建日历之后,您会在日历上调用设置时间。 – 2015-02-07 18:11:11
你的设定时间是什么意思? – Turo 2015-02-07 18:13:16