将用户输入日期与当前日期进行比较

kyp*_*ype 9 java calendar date simpledateformat

您好我试图将用户输入的日期(作为字符串)与当前日期进行比较,以便确定日期是更早还是更早.

我目前的代码是

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

}
Run Code Online (Sandbox Code Playgroud)

我试图将用户输入日期和当前日期都放入两个Date对象,以便我可以使用Date.compareTo()来简化比较日期.

我能够将用户输入字符串解析为Date对象.但是,当前日期cal.getTime().toString()由于是无效字符串而不会解析为Date对象.

怎么去做这个?提前致谢

rol*_*lfl 8

您可以获得最新信息Date:

todayDate = new Date();
Run Code Online (Sandbox Code Playgroud)

编辑:由于你需要比较日期而不考虑时间组件,我建议你看到这个:如何比较没有时间部分的两个日期?

尽管一个答案的"形式不佳",我实际上非常喜欢它:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您已经拥有:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");
Run Code Online (Sandbox Code Playgroud)

所以我会考虑(为了简单而不是表现):

todayDate = dateFormatter.parse(dateFormatter.format(new Date() ));
Run Code Online (Sandbox Code Playgroud)