Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

How to check if a date is after today java

Im trying to check whether a date entered by the user is after todays date. Here is my code:

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

Date is a variable with the user date in the format "2016/04/26". After doing some debugging i found that enteredDate and currentDate are null. Any ideas why this is? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in comments, it's not possible that Date object will have null reference. However if sdf.parse(date) throws an exception which is suppressed then enteredDate could be 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...