如何检查日期是否在今天之后 [英] How to check if a date is after today java

查看:82
本文介绍了如何检查日期是否在今天之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查用户输入的日期是否晚于今天.这是我的代码:

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是用户日期格式为"2016/04/26"的变量.经过一些调试后,我发现enterDate和currentDate为null.任何想法为什么会这样? 谢谢

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

推荐答案

如注释中所述,Date对象不可能具有空引用.但是,如果sdf.parse(date)抛出被抑制的异常,则enterDate可以为null.

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

这篇关于如何检查日期是否在今天之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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