Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a Date, allowing null

Tags:

java

date

I'm trying to print a Date, just the way DateFormat.getDateTimeInstance() does it.

format throws a NullPointerException when passing null, so I've been wondering if there is a different approach that would return null (or "null") instead?

Something I'd call instead of

Date d = null;
System.out.println(d==null ? null : DateFormat.getDateTimeInstance().format(d));
like image 387
Peter Lang Avatar asked Mar 25 '11 12:03

Peter Lang


2 Answers

You could just wrap the call inside a utility method :

public class DateUtils {
    public static String formatDateTime(Date dateOrNull) {
        return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
    }
}

private constructor and javadoc omitted for brevity.

like image 111
JB Nizet Avatar answered Sep 19 '22 15:09

JB Nizet


What's the problem with your existing code?

null is kind of a special case, and you've decided that you want one particular behaviour in this case (returning "null") instead of another particular behaviour (throwing an NPE). It's arguably cleaner to express this via switching at the top level rather than burying this logic within the formatting method.

It might be a little cleaner to use a full if-else rather than a tertiary operator, though, to make it clearer that there are two distinct branches (normal, and special-cased null):

if (d == null) {
    return "null"; // or whatever special case
}
else {
    return DateFormat.getDateTimeInstance().format(d);
}

The return value in the null case should be made clear in your method's javadocs, too.

like image 24
Andrzej Doyle Avatar answered Sep 18 '22 15:09

Andrzej Doyle