【问题标题】:Comparing user input date with current date将用户输入日期与当前日期进行比较
【发布时间】: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,因为输入的日期是今天(无论时间如何)。
  • 对于这个问题的新读者,我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter

标签: java date calendar simpledateformat


【解决方案1】:

您可以通过以下方式获取当前的Date

todayDate = new Date();

编辑:由于您需要比较日期而不考虑时间部分,我建议您查看:How to compare two Dates without the time portion?

尽管一个答案的“糟糕的形式”,但我实际上非常喜欢它:

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

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

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

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

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

【讨论】:

  • 谢谢。这会将当前时间信息也存储到日期中吗?
  • 是的,如果需要,您可以将其删除。
  • 我必须把它放到日历中才能修改时间对吧?由于 Date.setHour 已经折旧
  • 为什么要修改时间?
  • 因为我只想根据日期(而不是时间)将用户输入日期与当前日期进行比较。 compareTo() 也比较时间,因此我想将时间设置为 00:00:00 以消除时间比较问题
【解决方案2】:

这里是检查给定日期时间是否大于当前日期时间的代码。下面的方法将特定的日期时间字符串作为参数,如果提供 date-返回 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);
 }

【讨论】:

    【解决方案3】:

    你可以这样做。

    // 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
    }
    

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

    【讨论】:

      【解决方案4】:
       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();
                              }
       } }
      

      【讨论】:

        【解决方案5】:

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

        所以:

            Date currentDate = new Date();
        

        会做好的

        【讨论】:

          【解决方案6】:

          Fomat 不符合您的预期。

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

          输出 : Fri Nov 01 13:46:52 EET 2013

          【讨论】:

            【解决方案7】:

            java.time

            我建议您使用现代 Java 日期和时间 API java.time 进行日期工作。

                ZoneId zone = ZoneId.of("America/Santarem");
                LocalDate today = LocalDate.now(zone);
                
                String userInput = "14-04-2021";
                LocalDate myDate = LocalDate.parse(userInput, DATE_PARSER);
                
                if (myDate.isBefore(today)) {
                    System.out.println(userInput + " is in the past.");
                } else if (myDate.isAfter(today)) {
                    System.out.println(userInput + " is in the future.");
                } else {
                    System.out.println(userInput + " is today.");
                }
            

            输出是:

            14-04-2021 已经过去了。

            我使用这个格式化程序进行解析:

            private static final DateTimeFormatter DATE_PARSER
                    = DateTimeFormatter.ofPattern("dd-MM-uuuu");
            

            你的代码出了什么问题?

            我评论了你得到异常的那一行:

                        // trying to parse current date here
                        newDate = dateFormatter.parse(cal.getTime().toString()); //throws exception
            

            果然我得到了这个例外:

            java.text.ParseException:无法解析的日期:“Fri Apr 16 07:37:00 CEST 2021"

            您的SimpleDateFormat 尝试解析dd-MM-yyyy 格式的字符串。 cal.getTime() 返回 DatetoString() 上的 Date 的值看起来像异常所说的 Fri Apr 16 07:37:00 CEST 2021。这不是dd-MM-yyyy 格式(甚至不接近)。这就是解析失败并出现您看到的异常的原因。

            使用 java.time 根本没有必要解析今天的日期,因为您没有将它作为字符串获取。使用 Java 1.0 和 1.1 中旧的和麻烦的日期类,它可以被用作摆脱 Date 的时间部分的技巧,但当时也不是推荐的方式。

            链接

            Oracle tutorial: Date Time 解释如何使用 java.time。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-08-21
              • 1970-01-01
              • 2013-06-12
              • 2017-05-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多