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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!