Java 使用 Date 对象进行空检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34944182/
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-11 16:09:11  来源:igfitidea点击:

null check with Date object

javadate

提问by maman

My method takes a Date object. And I am passing a null value.How can I check if the (Date date) date is null or not.I am new in Stackoverflow, If the question is not a good one please don't undergrade the post.

我的方法需要一个 Date 对象。我正在传递一个空值。如何检查(日期日期)日期是否为空。我是 Stackoverflow 的新手,如果问题不是一个好问题,请不要给帖子评分。

回答by James

Check if it is null:

检查它是否为空:

if (date == null) {...}

Check if it is not null:

检查它是否不为空:

if (date != null) {...}

回答by Aaron

In Java 8 you could use an Optional<Date>and check its empty()or isPresent()methods.

在 Java 8 中,您可以使用 anOptional<Date>并检查其empty()isPresent()方法。

回答by Raju

You can check with an if-else statement, like this:

您可以使用 if-else 语句进行检查,如下所示:

if (date.equals(null)) {
    //something
} else {
    //something
}

回答by Anand Pandey

Java Code : Check if date is null

Java 代码:检查日期是否为空

    public static void main( String[] args )
        {           
            Date date = showDate();
            //check with if-else statement with equals()
            if ( !date.equals( null ) )
            {
                System.out.println( "hi" );
            }
            else
            {
                System.out.println( "hello" );
            }
            //check with if-else statement with = oprator
            if ( date!= null )
            {
                System.out.println( "hi" );
            }
            else
            {
                System.out.println( "hello" );
            }
        }

        public static Date showDate(){
            return new Date();

        }