比较用户输入日期和当前日期 [英] Comparing user input date with current date

查看:58
本文介绍了比较用户输入日期和当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi im trying to compare a user inputted date (as a string) with the current date so as to find out if the date is earlier or older.

我当前的代码是

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()来简化比较日期.

Im trying to get both user input date and current date into two Date objects, so that i can use Date.compareTo() to simplify comparing dates.

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

I was able to parse the user input string into the Date object. However the current date cal.getTime().toString() does not parse into the Date object due to being an invalid string.

如何执行此操作?预先感谢

How to go about doing this? Thanks in advance

推荐答案

您可以通过以下方式获取当前的日期:

You can get the current Date with:

todayDate = new Date();

由于您需要比较日期而不考虑时间部分,因此我建议您看到以下内容:

Since you need to compare the dates without considering the time component, I recommend that you see this: How to compare two Dates without the time portion?

尽管一个答案的形式很差,但我实际上还是很喜欢:

Despite the 'poor form' of the one answer, I actually quite like it:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));

就您而言,您已经拥有:

In your case, you already have:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy");

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

so I would consider (for simplicity rather than performance):

todayDate = dateFormatter.parse(dateFormatter.format(new Date() ));

这篇关于比较用户输入日期和当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆