How can I avoid a NullPointerException
here if the user passes a null value for a date? Ideally, I would use a simple if statement.
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
String layupDate = dateFormatter.format(orderLayupDateSet.getLayupDate());
String layupTime = timeFormatter.format(orderLayupDateSet.getLayupDate());
if(layupDate == null) {
}
You validate the date (orderLayupDateSet.getLayupDate()
) in a liner (just creating a new date if null here but you can do as you please);
(orderLayupDateSet.getLayupDate() == null) ? new Date() : orderLayupDateSet.getLayupDate()
You can also go the traditional
if (orderLayupDateSet.getLayupDate() == null) {
orderLayupDateSet.setLayupDate(new Date());
}
Or you can do it the other way around with a utility, and calling the utility function to check for you - seeing that you return a String in your example above. Like the below;
public class DateUtils {
public static String formatDateTime(Date dateOrNull) {
return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
}
}
Which in your code can be
String layupDate = (orderLayupDateSet == null || orderLayupDateSet.getLayupDate() ? null : dateFormatter.format(orderLayupDateSet.getLayupDate()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With