如何检查日期是否在今天的java之后

时间:2016-04-25 12:00:14

标签: java date parsing simpledateformat

我试图检查用户输入的日期是否在今天的日期之后。这是我的代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date enteredDate = sdf.parse(date);
Date currentDate = new Date();
if(enteredDate.after(currentDate)){

日期是一个变量,其用户日期格式为“2016/04/26”。做了一些调试后,我发现enteredDate和currentDate为null。任何想法为什么会这样? 感谢

3 个答案:

答案 0 :(得分:1)

正如评论中所提到的,Date对象不可能具有空引用。但是,如果sdf.parse(date)抛出一个被抑制的异常,那么enteredDate可以为null。

 String date="2016/04/26";
    Date enteredDate=null;
    try
    {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    enteredDate = sdf.parse(date);
    }catch (Exception ex)
    {
        // enteredDate will be null if date="287686";
    }
    Date currentDate = new Date();      
    if(enteredDate.after(currentDate)){
        System.out.println("after ");
    }else
        System.out.println("before");

答案 1 :(得分:-2)

public class App {
    public static void main(String[] args) {
        String date = "2016/04/26";
        Date enteredDate = null;
        Date matcher = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        try {
            enteredDate = sdf.parse(date);
        } catch (Exception ex) {
            ex.printStackTrace();// enteredDate will be null if date="287686";
        }

        try {
            matcher = sdf.parse("2016/04/26");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        }

        if (enteredDate.compareTo(matcher) == 0) {
            System.out.println("enteredDate will be null");
        }

        Date currentDate = new Date();
        if (enteredDate.after(currentDate)) {
            System.out.println("after ");
        } else
            System.out.println("before");
    }
}

答案 2 :(得分:-2)

java日期类有前后方法,你可以使用一个很好的例子就是这个

`import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.text.ParseException;
 public class App 
 {
     public static void main( String[] args ) 
     {
     try{

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31");
        Date date2 = sdf.parse("2010-01-31");

        System.out.println(sdf.format(date1));
        System.out.println(sdf.format(date2));

        if(date1.compareTo(date2)>0){
            System.out.println("Date1 is after Date2");
        }else if(date1.compareTo(date2)<0){
            System.out.println("Date1 is before Date2");
        }else if(date1.compareTo(date2)==0){
            System.out.println("Date1 is equal to Date2");
        }else{
            System.out.println("How to get here?");
        }

    }catch(ParseException ex){
        ex.printStackTrace();
    }
}
}`