【发布时间】:2013-11-01 11:44:41
【问题描述】:
您好,我正在尝试将用户输入的日期(作为字符串)与当前日期进行比较,以确定日期是否更早或更早。
我当前的代码是
String date;
Date newDate;
Date todayDate, myDate;
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
while(true)
{
Scanner s = new Scanner (System.in);
date = s.nextLine();
Calendar cal = Calendar.getInstance();
try {
// trying to parse current date here
// newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception
// trying to parse inputted date here
myDate = dateFormatter.parse(date); //no exception
} catch (ParseException e) {
e.printStackTrace(System.out);
}
}
我试图将用户输入日期和当前日期都放入两个 Date 对象中,以便我可以使用 Date.compareTo() 来简化比较日期。
我能够将用户输入字符串解析为 Date 对象。但是当前日期 cal.getTime().toString() 由于是无效字符串,因此不会解析到 Date 对象中。
怎么做呢?提前致谢
【问题讨论】:
-
澄清一下 - 如果输入的日期是昨天,您想要返回
true的东西,但如果输入的日期是今天,则返回false。对吗? -
是的,这就是我想要做的。假设我今天运行程序,newDate = new Date();给我(2013 年 11 月 1 日晚上 8 点),如果用户输入 2013 年 11 月 1 日,它应该返回 false,因为输入的日期是今天(无论时间如何)。
-
对于这个问题的新读者,我建议你不要使用
SimpleDateFormat和Date。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDate和DateTimeFormatter。
标签: java date calendar simpledateformat