How to Check if a Date is Empty (null) or not in Java


If you have a date in Java as Date, LocalDate, or Instant and you want to know if it is empty or not then you should do a null check on your date reference.


Example:

package org.code2care.examples;

import java.time.LocalDate;

public class Example {

    public static void main(String... args) {

        LocalDate date = null; //assuming null

        if (date == null) {
            System.out.println("Date is empty (null).");
        } else {
            //your logic
            System.out.println("Date is not empty.");
        }
    }
}

Let's see the same example using Optional.

package org.code2care.examples;

import java.time.LocalDate;
import java.util.Optional;

public class Example {

    public static void main(String... args) {

        LocalDate date = null; // assuming null

        Optional dateOptional = Optional.ofNullable(date);

        String message = dateOptional.map(d -> "Date is not empty.")
                                    .orElse("Date is empty (null).");

        System.out.println(message);
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap