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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19726115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:43:26  来源:igfitidea点击:

Comparing user input date with current date

javadatecalendarsimpledateformat

提问by kype

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.

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

My current code is

我目前的代码是

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

}

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 对象中,以便我可以使用 Date.compareTo() 来简化比较日期。

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.

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

How to go about doing this? Thanks in advance

怎么做呢?提前致谢

采纳答案by rolfl

You can get the current Datewith:

您可以通过以下方式获取电流Date

todayDate = new Date();

EDIT: 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() ));

回答by Ahmet Karakaya

Fomat does not comply as you expect.

Fomat 不符合您的预期。

 Calendar cal = Calendar.getInstance();
      System.out.println(cal.getTime().toString());

output : Fri Nov 01 13:46:52 EET 2013

输出:EET 2013 年 11 月 1 日星期五 13:46:52

回答by Dawood ibn Kareem

You can do this.

你可以这样做。

// Make a Calendar whose DATE part is some time yesterday.
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, -1);

if (myDate.before(cal.getTime())) {
    //  myDate must be yesterday or earlier
} else {
    //  myDate must be today or later
}

It doesn't matter that calhas a time component, because myDatedoesn't. So when you compare them, if caland myDateare the same date, the time component will make callater than myDate, regardless of what the time component is.

cal有时间分量并不重要,因为myDate没有。因此,当您比较它们时,如果calmyDate是相同的日期,则无论时间组件是什么,时间组件都会cal晚于myDate

回答by Gigalala

Creating a new Date() will give you a Date object with the current date.

创建一个新的 Date() 将为您提供一个带有当前日期的 Date 对象。

so:

所以:

    Date currentDate = new Date();

will do the job

会做这份工作

回答by ThmHarsh

Here is the code to check if given date-time is larger then the Present Date-time.Below method takes perticular date-time string as argument and returns trueif provided date-time is larger then the present date-time. #thmharsh

这是检查给定日期时间是否大于当前日期时间的代码。Below 方法将特定日期时间字符串作为参数,如果提供的日期时间大于当前日期时间,则返回 true。#thmharsh

private boolean isExpire(String date){
    if(date.isEmpty() || date.trim().equals("")){
        return false;
    }else{
            SimpleDateFormat sdf =  new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss a"); // Jan-20-2015 1:30:55 PM
               Date d=null;
               Date d1=null;
            String today=   getToday("MMM-dd-yyyy hh:mm:ss a");
            try {
                //System.out.println("expdate>> "+date);
                //System.out.println("today>> "+today+"\n\n");
                d = sdf.parse(date);
                d1 = sdf.parse(today);
                if(d1.compareTo(d) <0){// not expired
                    return false;
                }else if(d.compareTo(d1)==0){// both date are same
                            if(d.getTime() < d1.getTime()){// not expired
                                return false;
                            }else if(d.getTime() == d1.getTime()){//expired
                                return true;
                            }else{//expired
                                return true;
                            }
                }else{//expired
                    return true;
                }
            } catch (ParseException e) {
                e.printStackTrace();                    
                return false;
            }
    }
}


  public static String getToday(String format){
     Date date = new Date();
     return new SimpleDateFormat(format).format(date);
 }

回答by Prajwal W

 public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.

for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

SimpleDateFormat sdf1234 = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
                    String abs12 = value.getExpiryData();

                    Date todayDate = new Date();

                    try {
                        Date testDate1 = sdf1234.parse(abs12);

                        if(testDate1.compareTo(todayDate) <0){//  expired
                            dataSnapshot1.getRef().removeValue();
                        }
                        else if(testDate1.compareTo(todayDate)==0){// both date are same
                            if(testDate1.getTime() == todayDate.getTime() || testDate1.getTime() < todayDate.getTime())
                            {//  expired
                                dataSnapshot1.getRef().removeValue();
                            }
                            else
                                {//expired
                                //Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
                            }
                        }else{//expired
                           // Toast.makeText(getApplicationContext(),"Successful praju ",Toast.LENGTH_SHORT).show();
                        }
 } }