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);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!